phparraysmultidimensional-arraysumarray-reduce

Sum each row's deep values in a 3-dimensional array


I have need to calculate the sum of the deep elements foreach first level element.

Sample 3-level array:

[
    1 => [
        'A' => ['AA' => 3, 'AB' => 5],
        'B' => ['BA' => 2]
    ],
    2 => [
        'C' => ['CA' => 4],
        'D' => ['DA' => 1, 'DB' => 2]
    ],
    3 => [
        'E' => ['EA' => 1, 'EB' => 2, 'EC' => 3],
        'F' => ['FA' => 0, 'FB' => 7, 'FC' => 7]
    ]
]

I want to sum the values and this is my expectation:

Array(
    [1] => 10        
    [2] => 7
    [3] => 20
)

Here is my code that I used for summing the value:

$total[$country_id][$province_id][$city_id] = $amount;

$result = array();
foreach( $total as $key => $val ){
         $total[$key] = array_sum ( $val );
}

Can someone explain what is wrong with my code or explain how foreach work? The result of my code is 0 and actually I just studied around 1 week about foreach.


Solution

  • As you want to know more about foreach, here is a more verbose solution using it :

    $total = 0;
    $totalByCountry = [];
    
    // iterate over each country
    foreach ($arr as $countryId => $provinces) {
    
        $totalByCountry[$countryId] = 0;
    
        // iterate over each province
        foreach ($provinces as $provinceId => $cities) {
    
            // iterate over each city
            foreach ($cities as $cityId => $value) {
                $totalByCountry[$countryId] += $value;
                $total += $value;
            }
        }
    }
    

    Result of var_dump(totalByCountry) :

    array (size=3)
        1 => int 10
        2 => int 7
        3 => int 20
    

    Result of var_dump($total) :

    int 37
    

    -- edit --

    In real world project, you better be less verbose and use php functions made for this kind of situation like array_walk_recursive(), as in Philipp Maurer and Firoz Ahmad answers.