0

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.

2
  • What programming language is this? What code do you currently have? Please edit to include a minimal reproducible example - don't use the output of a debug function, write an actual hard-coded input that someone can use directly in their answer. Commented Mar 18, 2022 at 17:56
  • There I go. Can you please check? @IMSoP Commented Mar 18, 2022 at 18:36

1 Answer 1

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

)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.