0

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.

1
  • What result do you get when you take the sum of the values in the array? Commented Sep 30, 2011 at 21:31

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Or even easier:

function crash_reporter($evaluation){

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

Comments

0

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.