对二维数组中的所有列值求和以生成总计的关联一维数组

问题描述 投票:0回答:2

我想将条目求和到一个数组(动态数组,从数据库中获取的数据)并返回每个条目的总和。多维数组具有以下形状:

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

我想要做的是将“term_1_mid”中样本数组的值添加到“term_1_end”中相同样本数组的值...所以得到的求和输出应该类似于:

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

有什么办法可以实现这个目标吗?

我尝试了以下代码,但它似乎不起作用:

<?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);
php arrays multidimensional-array sum
2个回答
2
投票

这是问题的解决方案。

    <?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>";
     }
     ?>

输出:

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

1
投票

这是演示

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

$arrSum =[];
foreach($sample as $term=>$termname){
    foreach($termname as $sub=>$mark){
        if(!isset($arrSum[$sub])){$arrSum[$sub] = 0;}
        $arrSum[$sub] += $mark;
    }
}
print_r($arrSum);
© www.soinside.com 2019 - 2024. All rights reserved.