Try this:
$reduced = $data->groupBy('sku')->map(function ($items) {
$item = $items->first();
$item['quantity'] = $items->sum('quantity');
return $item;
});
I have a multi-dimensional array that i want to loop through and find any key/value duplicates. If there is a duplicate i want to add the quantities together and then remove one of them from my array (array_filter).
For example, this is my Array of Arrays. If there is a duplicate sku => i want to add their quantities together and then remove one from the array based on the ID (it will always be unique).
DEP1030BLKCO - this sku is duplicated twice. So i would like to add their quantities together (8+8) and remove one of their keys so its a single DEP1030BLKCO sku with quantity of 16.
I know that i can initialize an array variable $duplicates to store IDs of duplicates and then use an array filter function to filter out any IDs added to the array (essentially removing duplicates) but how can i find the duplicates? I saw array_unique but im unsure if that will help in this situation.
Is there a better approach than *this?
Array (
[DEP2000RODSIDL2] => Array
(
[product_id] => 167
[sku] => DEP2000RODSIDL2
[name] => Side Rod - Large
[weight] => 1.00
[quantity] => 32
[product_options] =>
[id] => DEPRODSIDL
)
[1DEP1030BLKL] => Array
(
[product_id] => 173
[sku] => DEP30BLKL
[name] => Large Black
[weight] => 12
[quantity] => 1
[product_options] =>
[id] => 1DEP30BLKL
)
[1DEP1030BLKM] => Array
(
[product_id] => 168
[sku] => DEP30BLKCO
[name] => Black Carry
[weight] => 8
[quantity] => 1
[product_options] =>
[id] => 8952
)
[1DEP1030BLKCO] => Array
(
[product_id] => 168
[sku] => DEP30BLKCO
[name] => Black Carry
[weight] => 8
[quantity] => 1
[product_options] =>
[id] => 1DEP30BLKCO
)
)
Please or to participate in this conversation.