开发者

Make sum of an array php

I'm having a 2 dimensional array what is passed by a function what's looks as it follows

function crash_reporter($evaluation){

foreach ($evaluation as $agent){    
开发者_JAVA百科
    unset($agent['time']);


    print_r($agent);

}

than I'm getting the following array and I'm struggling to get the sum of the indexed values.

Array
(
    [agent_example1] => 0
    [agent_example2] => 2
    [agent_example3] => 0
    [agent_example4] => 1
    [] => 0
)
Array
(
    [agent_example1] => 0
    [agent_example2] => 1
    [agent_example3] => 0
    [agent_example4] => 0
    [] => 0
)
Array
(
    [agent_example1] => 0
    [agent_example2] => 3
    [agent_example3] => 0
    [agent_example4] => 0
    [] => 0
)

        )
)

result should be int. 7


You may want to try something like this:

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


Or even easier:

function crash_reporter($evaluation){

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


You can sum the sums of each sub-array ($agent), after your foreach/unset loop, like:

$sum = array_sum(array_map('array_sum', $evaluation));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜