I have the following two stdClass array from a loop. Now I need to merge them when when the key 'id' matches.
array (size=1)
0 =>
object(stdClass)[28]
public 'id' => string '78' (length=2)
public 'quantity' => string '5' (length=1)
array (size=1)
1 =>
object(stdClass)[31]
public 'product_id' => string '78' (length=2)
public 'quantity' => string '1' (length=1)
So the final array become
array (size=1)
1 =>
object(stdClass)[31]
public 'product_id' => string '78' (length=2)
public 'quantity' => string '6' (length=1)
Any help on how to do that ? I decode the original data using json_decode from [{"id":"78","quantity":"1"}]
this format of data.
If you add an extra parameter to the json_decode
, you can get the data as an associative array, which is much easier to work with. I've done a couple of versions ( the first is PHP 7 ), pick one which works with your system.
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$arr1 = json_decode('[{"id":"78","quantity":"1"}, {"id":"79","quantity":"3"}]', true);
$arr2 = json_decode('[{"id":"78","quantity":"5"}]', true);
$arr3 = array_merge($arr1, $arr2);
// V7
$result = [];
foreach ( $arr3 as $element ) {
$result[$element['id']] = ($result[$element['id']]??0)
+ $element['quantity'];
}
print_r($result);
// Prior to V7
$result = array();
foreach ( $arr3 as $element ) {
if ( !isset($result[$element['id']]) ){
$result[$element['id']] = 0;
}
$result[$element['id']] += $element['quantity'];
}
print_r($result);
I've added another element to show how this adds up, but the output of this is...
Array
(
[78] => 6
[79] => 3
)
Array
(
[78] => 6
[79] => 3
)