Search code examples
phparraysmultidimensional-arraysum

Sum all column values in a 2d array to produce an associative 1d array of totals


I want to sum entries to an array (dynamic array, data being taken from the database) and return sum of each entry. The multidimensional array has the following shape:

<?php
$sample = array(
    "term_1_mid" => array(
        "English" => 56,
        "Mathematics" => 34,
        "Creative Arts" => 87
    ),
    "term_1_end" => array(
        "English" => 67,
        "Mathematics" => 59,
        "Creative Arts" => 95
    )
);

What I want to do is add the values of the sample array in "term_1_mid" to the values of the same sample array in "term_1_end"... So the resulting summation output should be something like:

<?php
$result = array(
    "English" => 123, // 56 + 67 from above
    "Mathematics" => 93, // 34 + 59
    "Creative Arts" => 182 // 87 + 95
);

Is there any way I could achieve this?

I tried the following code but it doesn't seem to work:

<?php
$final_score = [];

array_push($final_score, array_map(function($arr, $arr1) {
return $arr + $arr1;
}, $sample["term_1_mid"], $sample["term_1_end"]));

print_r($final_score);

Solution

  • Here is the solution for the problem.

        <?php
        $sample = array(
              "term_1_mid" => array(
                   "English" => 56,
                   "Mathematics" => 34,
                   "Creative Arts" => 87),
              "terrm_1_end" => array(
                   "English" => 67,
                   "Mathematics" => 59,
                   "Creative Arts" => 95)
              );
    
         # Initializing array to store the result
         $output_array = array();
    
         # Loop for adding the values
         foreach($sample as $sample_key => $sample_value){
             foreach ($sample_value as $key => $value){
                 $output_array[$key] += $value;
             }
         }
    
         # To check the data in array
         foreach($output_array as $key => $value){
             # used br tag only to show the each values in each line
             echo $key . " => ". $value . "<br>";
         }
         ?>
    

    Output :

    English => 123
    Mathematics => 93
    Creative Arts => 182