Click here to Skip to main content
15,891,372 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Quote:
I got an array which is repeating after a sequence by "id" and I am comparing an array with another multidimensional array with "id". If "id" exist in both array it returns value else it returns 0.

PHP
<pre>
<?php 
$arr1 = [
  ['id' => 6],
  ['id' => 7],
  ['id' => 8],
  ['id' => 9]
];

$arr2 = [
  ['id' => 6, 'total' => 84.75, 'group' => 1000],
  ['id' => 8, 'total' => 75.0, 'group' => 1000]
];

$s_data = [];

for($x = 0; $x < count($arr2); $x++){
    $id = $arr2[$x]['id'];
    $group = $arr2[$x]['group'];
    $total = $arr2[$x]['total'];


    for($ab = 0; $ab < count($arr1); $ab++){

        if($arr1[$ab]['id'] === $id)
       {
         $s_data[] = ['group' => $group, 'id' => $id, 
         'total'=> $total];
       }
       else
       {
         $s_data[] = ['group' => $group, 'id' => 
         $arr1[$ab]['id'], 'total'=> 0];                                
       }                             
      }

}
echo json_encode($s_data);
?>



I need a output like
array:4 [▼
  0 => array:3 [▼
    "group" => "1000"
    "id" => 6
    "total" => 84.75
  ]
  1 => array:3 [▼
    "group" => "1000"
    "id" => 7
    "total" => 0
  ]
  2 => array:3 [▼
    "group" => "1000"
    "id" => 8
    "total" => 75.0
  ]
  3 => array:3 [▼
    "group" => "1000"
    "id" => 9
    "total" => 0
  ]
]


What I have tried:

$arr1 = [
    [ 'id' => 6 ],
    [ 'id' => 7 ],
    [ 'id' => 8 ],
    [ 'id' => 9 ]
];

$arr2 = [
    [ 'id' => 6, 'total' => 84.75, 'group' => 1000 ],
    [ 'id' => 8, 'total' => 75.0, 'group' => 1000 ]
];

$result = [];

foreach ($arr1 as $value) {
  $filtered = array_filter($arr2, fn($item) => $item['id'] === $value['id']);
  if (count($filtered) === 1) {
    $result[] = array_values($filtered)[0];
  } else {
    $result[] = [ 'id' => $value['id'], 'total' => 0, 'group' => 1000 ];
  }
}

print_r($result);


I am getting some errors.
Posted
Comments
Richard Deeming 21-Mar-22 8:02am    
If you want someone to help you fix errors in your code, you need to explain precisely what errors you are getting. Simply saying "I am getting some errors" tells us precisely nothing.

Click the green "Improve question" link and update your question to include the full details of the errors you're getting. Remember to indicate which line of code each error relates to.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900