开发者

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

开发者 https://www.devze.com 2023-02-06 04:58 出处:网络
Let\'s say I have the following array and I want to add up the sub-array values using PHP: $summary = array(

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!


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


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


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.


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号