Reputation: 27
I have this array that has other arrays in each key, it has the product_id
keys in each of the sub arrays and their values are unknown. How do I get the total the value of the item_quantity
keys that share the same product_id
value?
Array (
[0] => Array ([product_id] => 17 [item_quantity] => 4)
[1] => Array ([product_id] => 17 [item_quantity] => 4)
[2] => Array ([product_id] => 18 [item_quantity] => 6)
)
I have no idea of which php function to use, but in a general term I would be "getting all item_quantity in the subarrays of an array where product_id in subarrays is the same".
EDIT : I think I missed that I also want to get the total of all the item_quantity
of every unique product_id
, that means that I want to not only get that of 17
but also of 18
.
Upvotes: 1
Views: 55
Reputation: 806
I think you are looking for something like this
$sum = array();
foreach ($array as $value) {
if( !isset($sum[$value["product_id"]]) )
$sum[$value["product_id"]] = 0;
$sum[$value["product_id"]] += $value["item_quantity"];
}
print_r($sum);
In your case output will be
Array ( [17] => 8 [18] => 6 )
The item_quantity
with same product_id
will be added in the same offset in the $sum
array.
Upvotes: 1