phpmultidimensional-arraysumfilteringkeypaths

Sum values in an associative multidimensional array according to a predefined and potentially incomplete key path


I have problem with my arrays and array_sum() function.

This code is not working properly. I have commented what it should be printed.

$teams[1]['AREA I']['blue'] = 30;
$teams[1]['AREA I']['green'] = 25;
$teams[1]['AREA II']['blue'] = 15;
$teams[2]['AREA I']['blue'] = 40;

echo array_sum($teams[1]); // 30+25+15=70
echo array_sum($teams[1]['AREA I']); // 30+25=55
echo array_sum($teams[1]['AREA I']['blue']); // 30

Solution

  • Have a look on below solution, hope it will help you to get desire result. I used iterator to iterate array:

    function getSum($array){
        if(is_array($array)) {
            $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
            $sum = 0;
            foreach ($iterator as $key => $value) {
                $sum += $value;
            }
        } else{
            $sum = $array;
        }
        return $sum;
    }
    
    $teams = array();
    $teams[1]['AREA I']['blue'] = 30;
    $teams[1]['AREA I']['green'] = 25;
    $teams[1]['AREA II']['blue'] = 15;
    $teams[2]['AREA I']['blue'] = 40;
    
    echo getSum($teams); //output: 110
    echo getSum($teams[1]); //output: 70
    echo getSum($teams[1]['AREA I']); //output: 55
    echo getSum($teams[1]['AREA I']['blue']); //output: 30