Search code examples
phpmultidimensional-arrayforeachsum

How to sum multi-dimensional arrays in PHP without merging values


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!


Solution

  • $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)
      }
    }