theOzmic theOzmic - 11 months ago 43
PHP Question

How to get values in an array that shares an element with other arrays in a multidimensional array with PHP

I have this array that has other arrays in each key, it has the

keys in each of the sub arrays and their values are unknown. How do I get the total the value of the
keys that share the same

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
of every unique
, that means that I want to not only get that of
but also of

Answer Source

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"];


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 $sumarray.