计算二维数组所有行中所有值的总和

问题描述 投票:0回答:3

我有一个二维数组,我需要获得值的总和。

[
    [
        'agent_example1' => 0,
        'agent_example2' => 2,
        'agent_example3' => 0,
        'agent_example4' => 1,
        '' => 0,
    ],
    [
        'agent_example1' => 0,
        'agent_example2' => 1,
        'agent_example3' => 0,
        'agent_example4' => 0,
        '' => 0,
    ],
    [
        'agent_example1' => 0,
        'agent_example2' => 3,
        'agent_example3' => 0,
        'agent_example4' => 0,
        '' => 0,
    ],
]

结果应该是

7

php arrays multidimensional-array sum cumulative-sum
3个回答
2
投票

您可能想尝试这样的事情:

function sum_2d_array($outer_array) {
    $sum = 0;
    foreach ($outer_array as $inner_array) {
        foreach ($inner_array as $number) {
            $sum += $number;
        }
    }
    return $sum;
}

1
投票

或者更简单:

function crash_reporter($evaluation){

    $sum = 0;
    foreach ($evaluation as $agent){    
        unset($agent['time']);
        $sum += array_sum($agent);
    }
    echo $sum;
}

0
投票

您可以在

$agent
循环之后对每个子数组 (
foreach/unset
) 的总和进行求和,例如:

$sum = array_sum(array_map('array_sum', $evaluation));
© www.soinside.com 2019 - 2024. All rights reserved.