如何找到关联数组的总和

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, ...)

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

Here's a sample algorithm:

  1. Use foreach on main array,
  2. Use foreach on second level array,
  3. Check if single color key exists in your target array
  4. If yes, do array_sum and add it to existing value
  5. If not, add new key with its sum to your target array

You can do like this

$tsales = array();
foreach ($sales as $key => $value) {
  foreach ($value as $key => $val) {
    $tsales[$key] += array_sum($val);
  }
}
echo '<pre>';
print_r($tsales);
echo '</pre>';

Try this:

$val = array();
foreach($sales as $values){
    foreach($values as $k => $v){
        $val[$k] = (array_key_exists($k, $val)) ? $val[$k] + array_sum($v) : array_sum($v);
    }
}

Output:

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

Here is short solution using array_walk, key_exists and array_sum functions:

$total = [];
array_walk($sales, function($v) use(&$total){
    foreach ($v as $k => $arr) {
        $total[$k] = (key_exists($k, $total))? $total[$k] + array_sum($arr) : array_sum($arr);
    }
});

print_r($total);

The output:

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