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.
<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.