1

Let's say I have the following array and I want to add up the sub-array values using PHP:

$summary = array(
    "person1" => array(
         question1 => '3',
         question2 => '5'),
    "person2" => array(
         question1 => '2',
         question2 => '3'),
    "person3" => array(
         question1 => '1',
         question2 => '2')
);

How can I output the individual array sums for each person, rather than totaling all values from all sub-arrays? For instance:

$summary = array(
    "person1" => array(
         questions => '8'),
    "person2" => array(
         questions => '5'),
    "person3" => array(
         questions => '3')
);

I seem to be able to add it up to 16 using a foreach loop, but what I need is individual values so I can get the highest value and lowest value.

Thanks in advance!

0

6 Answers 6

3

So you have an array of arrays and want to return an array of the sums of each subarray?

function sumArrays($array){
    return array_map("array_sum",$array);
}

All you'd need to do then, is call max on the returned array

Sign up to request clarification or add additional context in comments.

Comments

2
$summaryTotals = Array();
foreach ($summary as $_summary => $_questions)
  $summaryTotals[$_summary] = Array('questions'=>array_sum($_questions));
var_dump($summaryTotals);

Loop through all people, get the sum of the questions, and place them in the same key as they came from.


Output:

array(3) {
  ["person1"]=>
  array(1) {
    ["questions"]=>
    int(8)
  }
  ["person2"]=>
  array(1) {
    ["questions"]=>
    int(5)
  }
  ["person3"]=>
  array(1) {
    ["questions"]=>
    int(3)
  }
}

5 Comments

This seems like an awesome answer, but wouldn't I have to do two foreach loops? First loop through the summary array, then each subarray?
@TymArtist: It is, I'm just taking advantage of a built-in function of PHP, array_sum.
I used your solution and was able to get the result I wanted by adding a second foreach loop. Thanks!
May I ask what's different about the array you're running against and what you have posted? I was basing my solution off how you indented your array, and took liberties when it came to your (what I thought to be) missing syntax.
You know what, it was a tri-level array not a dual-level array, which probably accounts for the differential. I'll know next time to post the third level, it just seemed excessive :).
0

This ought to do it.

$summary = array();

foreach($data as $name => $questions)
{
    $sum = 0;
    foreach($questions as $question => $answer)
    {
        $sum += $answer;
    }
    summary[$name]['questions'] = $sum;
}

Initialize the sum value, sum up each set of questions, stash the sum value, and repeat until finished. You could put array_sum() into the mix instead of the inner foreach loop. I always forget about PHP's array functions. That would be this:

$summary = array();

foreach($data as $name => $questions)
{
    summary[$name]['questions'] = array_sum($questions);
}

Much shorter and probably more efficient.

Comments

0

You can iterate over the existing array, find the sum of marks for all questions for a given person and replace the existing value ( an array ) with the newly created array:

foreach($summary as $person => $person_arr) {
        $summary[$person] = array('question' => array_sum($person_arr));
}

See it

Comments

0

Simple function like:

function sumtwoDimensionalArrWithKey($twoDimensionalArr,$key_value){

    foreach($twoDimensionalArr as $twoDimensionalArrValue){
        foreach($twoDimensionalArrValue as $key=> $value){
            if ($key == $key_value) {
                $total += $value;
            }
        }    
    }

    return $total;
}

It can be called like:

echo sumtwoDimensionalArrWithKey($twoDimensionalArr,'field_name');

Comments

0

For functional-style syntax that delivers the exact desired output, call array_map() and return a new associative subarray contain the sum for each row encountered.

Code: (Demo)

var_export(
    array_map(fn($questions) => ['questions' => array_sum($questions)], $summary)
);

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.