I have an array of objects containing a partId and a quantity. I want for each partId in the final array to be unique, by summing the quantity of objects with the same partId.
I want this:
Array
(
[0] => stdClass Object
(
[partId] => 232032
[quantity] => 2
)
[1] => stdClass Object
(
[partId] => 232032
[quantity] => 1
)
[2] => stdClass Object
(
[partId] => 232031
[quantity] => 1
)
)
To end up like this:
Array
(
[0] => stdClass Object
(
[partId] => 232032
[quantity] => 3
)
[1] => stdClass Object
(
[partId] => 232031
[quantity] => 1
)
)
Here’s what I’m doing now, I feel like there has to be a better way.
$tmp = array();
foreach ($array1 as $item) {
if (array_key_exists($item->partId, $tmp)) {
$tmp[$item->partId]->quantity += $item->quantity;
} else {
$tmp[$item->partId] = $item;
}
}
$array2 = array_merge($tmp);
You are almost there: