PHP:对多维数组的不同值求和



我需要将'in'和'ou', [a]到[t]相加数组。

Array
(
[1] => Array
    (
        [in] => Array
            (
                [a] => 3
                [b] => 0
                [c] => 0
                [d] => 0
                [e] => 0
                [f] => 0
                [o] => 0
                [t] => 3
            )
        [ou] => Array
            (
                [a] => 0
                [b] => 0
                [c] => 1
                [d] => 0
                [e] => 0
                [f] => 0
                [o] => 0
                [t] => 1
            )
    )
[2] => Array
    (
        [in] => Array
            (
                [a] => 0
                [b] => 0
                [c] => 0
                [d] => 0
                [e] => 0
                [f] => 0
                [o] => 0
                [t] => 0
            )
        [ou] => Array
            (
                [a] => 0
                [b] => 0
                [c] => 0
                [d] => 1
                [e] => 2
                [f] => 0
                [o] => 0
                [t] => 3
            )
    )
)

下面是我如何计算合计'in'+'ou'。然而,当涉及到"in"a,b,c,d,e,f,t和"ou"a,b,c,d,e,f,t的个人总数时,我似乎陷入了窠臼。

//get day total
foreach($arr as $array){
    foreach($array as $inou){
        foreach(array_keys($inou) as $value){
            if(isset($total[$value])){
                $total[$value] += $inou[$value];
            }else{
                $total[$value] = $inou[$value];
            }
        }
    }
}

输出应该类似于

in(
[a] => 3
[b] => 0
[c] => 0
...
[t] => 3
)
ou(
[a] => 0
[b] => 0
[c] => 1
[d] => 1
[e] => 2
[f] => 0
[t] => 4
)

这应该可以让你开始:

        $sumIN = 0; 
        $sumOU = 0;
        foreach($arr as $innerArr)
        {
            $sumIN += array_sum($innerArr['in']);
            $sumOU += array_sum($innerArr['ou']);
        }

相关内容

  • 没有找到相关文章

最新更新