dpa89292 2018-03-20 02:11
浏览 222
已采纳

php - 如何从3维数组中求和一个值

I have data as below :

Array
(
    [1] => Array
        (
            [A] => Array
                (
                    [AA] => 3
                    [AB] => 5
                )

            [B] => Array
                (
                    [BA] => 2
                )

    [2] => Array
        (
            [C] => Array
                (
                    [CA] => 4
                )

            [D] => Array
                (
                    [DA] => 1
                    [DB] => 2
                )
        )

    [3] => Array
        (
            [E] => Array
                (
                    [EA] => 1
                    [EB] => 2
                    [EC] => 3
                )

            [F] => Array
                (
                    [FA] => 0
                    [FB] => 7
                    [FC] => 7
                )
)

I want to sum the value 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? because the result of my code is 0 and actually I just studied around 1 week about foreach. Thanks

展开全部

  • 写回答

4条回答 默认 最新

  • doukang7501 2018-03-20 02:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部