1
votes

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!

6
Are you missing a ) after question2 => '5' ? - codaddict
Yes...I typed this out and guess I forgot to add closing parens. Thanks for the note! - TymArtist

6 Answers

3
votes

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

2
votes
$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)
  }
}
0
votes

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.

0
votes

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

0
votes

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');
0
votes

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