I have 2 arrays. Something like this .
$res1 = [
['ID' => 60,'TOTAL' => 500],
['ID' => 61,'TOTAL' => 600],
['ID' => 63,'TOTAL' => 500]
];
$res2 = [
['ID' => 60,'TOTAL' => 600],
['ID' => 61,'TOTAL' => 700],
['ID' => 64,'TOTAL' => 800]
];
I want to merge $res1 and $res2 array with Ids and sum the totals if IDs are equal else if ids do not match, then I should keep that as well in array.
This is what I have tried and need help to improve it more in terms performance as well .
foreach ($res1 as $id1 => $val1) {
foreach ($res2 as $id2 => $val2) {
$r =array();
if ($val1['ID'] == $val2['ID']) {
$r['ID'] = $val1['ID'];
$r['TOTAL'] = $val1['TOTAL'] + $val2['TOTAL'];
}else{
// MISSING Something here
}
$result[] = $r;
}
}
Expected result should be
$result = [
['ID' => 60,'TOTAL' => 1100],
['ID' => 61,'TOTAL' => 1300],
['ID' => 63,'TOTAL' => 500],
['ID' => 64,'TOTAL' => 800]
];