Juice Juice - 6 months ago 129
PHP Question

How to find the sum of an associative array

i have an array like this

$sales = array('FIRST'=>array('RED'=>array(9,3),'GREEN'=>array(4,5,8,2)),
'SECOND'=>array('RED'=>array(3,5,5,2),'YELLOW'=>array(4,2,5)),
'THIRD'=>array('BLUE'=>array(1,2,4),'RED'=>array(9,4,6)),
'FOUR'=>array('BLUE'=>array(2,3,3,5),'BLACK'=>array(4,5,8,9)));


And i have to find the total sales of each color in the array.

The result array should be like

Array('RED'=>46,'GREEN'=>19, ...)

Answer

Use array_sum inside foreach:

$sales = array('FIRST'=>array('RED'=>array(9,3),'GREEN'=>array(4,5,8,2)), 
'SECOND'=>array('RED'=>array(3,5,5,2),'YELLOW'=>array(4,2,5)),
'THIRD'=>array('BLUE'=>array(1,2,4),'RED'=>array(9,4,6)), 
'FOUR'=>array('BLUE'=>array(2,3,3,5),'BLACK'=>array(4,5,8,9)));

$arr = [];

foreach ($sales as $value) {
    foreach ($value as $key => $val) {
        if(array_key_exists($key, $arr)){
            $arr[$key] += array_sum($val);
        } else {
            $arr[$key] = array_sum($val);
        }
    }
}

print_r($arr);

Result:

Array
(
    [RED] => 46
    [GREEN] => 19
    [YELLOW] => 11
    [BLUE] => 20
    [BLACK] => 26
)

Demo