'How to merge an array after comparing with another multidimensional arrays

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 
$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 an array 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
  ]
]

For your kind information I am comparing 2 array with id. If "id" exist in both array it returns value else it returns 0.



Solution 1:[1]

$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);

Output:

Array
(
    [0] => Array
        (
            [id] => 6
            [total] => 84.75
            [group] => 1000
        )

    [1] => Array
        (
            [id] => 7
            [total] => 0
            [group] => 1000
        )

    [2] => Array
        (
            [id] => 8
            [total] => 75
            [group] => 1000
        )

    [3] => Array
        (
            [id] => 9
            [total] => 0
            [group] => 1000
        )

)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lukas.j