PHP:通过键明智的数组求和

时间:2019-08-21 09:16:21

标签: php arrays

我有一个简单的问题,但对我来说似乎很复杂。我有一个像下面这样的数组。我想输出20、21、22、30、31、32键的总和。实际上,我已经按照自己的政策尝试过,但不会得到我想要的结果。

[P00000001] => Array
        (
            [20] => Array
                (
                    [0] => 12
                    [1] => 5.4
                    [2] => 8.9
                    [3] => 12                    
                ),
            [21] => Array
                (
                    [0] => 12
                    [1] => 4.4
                    [2] => 3.9
                    [3] => 16                    
                ),
            [22] => Array
                (
                    [0] => 13
                    [1] => 5.4
                    [2] => 8.9
                    [3] => 12                    
                ),
        ),
        [P00000002] => Array
        (
            [30] => Array
                (
                    [0] => 12
                    [1] => 5.4                    
                ),
            [31] => Array
                (
                    [0] => 12
                    [1] => 4.4
                    [2] => 3.9                                    
                ),
            [32] => Array
                (
                    [0] => 13
                    [1] => 5.4
                    [2] => 8.9
                    [3] => 12                    
                ),
        )

输出将如下所示。希望伙计,你明白我的意思。

[P00000001] => Array
        (
            [20] => 38.3
            [21] => 36.3
            [22] => 39.3
            ),
        [P00000002] => Array
        (
            [30] => 17.4
            [31] => 20.3
            [32] => 39.3
        )

1 个答案:

答案 0 :(得分:0)

您可以在下面的代码段中使用

foreach($arr as $key => &$val){
    foreach($val as $k => $v)
    {
        $val[$k] = array_sum($v); // in second inner loop
    }
}

Demo