What is the most effecient way to reduce (combine) an array containing objects?

vamsmooli

New Member
I have an array of objects containing a \[code\]partId\[/code\] and a \[code\]quantity\[/code\]. I want for each \[code\]partId\[/code\] in the final array to be unique, by summing the \[code\]quantity\[/code\] of objects with the same \[code\]partId\[/code\].I want this:\[code\]Array( [0] => stdClass Object ( [partId] => 232032 [quantity] => 2 ) [1] => stdClass Object ( [partId] => 232032 [quantity] => 1 ) [2] => stdClass Object ( [partId] => 232031 [quantity] => 1 ))\[/code\]To end up like this:\[code\]Array( [0] => stdClass Object ( [partId] => 232032 [quantity] => 3 ) [1] => stdClass Object ( [partId] => 232031 [quantity] => 1 ))\[/code\]Here's what I'm doing now, I feel like there has to be a better way.\[code\]$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);\[/code\]
 
Back
Top