lgt
lgt

Reputation: 1034

Calculate total sum of all values from all rows of a 2d array

I'm having a 2-dimensional array and I need to get the total sum of the values.

[
    [
        '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,
    ],
]

Result should be 7.

Upvotes: 0

Views: 264

Answers (4)

mickmackusa
mickmackusa

Reputation: 47864

While I would use salathe's solution for this specific scenario, I'll offer some alternatives.

You can visit all leafnodes with a functional-style script via array_walk_recursive() by passing the result variable as a modifiable reference.

Code: (Demo)

$result = 0;
array_walk_recursive(
    $array,
    function ($v) use (&$result) {
        $result += $v;
    }
);
var_export($result);  // 7

Or use a recursive iterator with a classic loop.

Code: (Demo)

$result = 0;
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::LEAVES_ONLY) as $value) {
    $result += $value;
} 
var_export($result);  // 7

Upvotes: 0

Dominic
Dominic

Reputation: 806

Or even easier:

function crash_reporter($evaluation){

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

Upvotes: 1

salathe
salathe

Reputation: 51950

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

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

Upvotes: 0

Jon Newmuis
Jon Newmuis

Reputation: 26492

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;
}

Upvotes: 2

Related Questions