猿问

php将一个多维数组与自身相加

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


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


慕田峪4524236
浏览 94回答 2
2回答

慕的地8271018

这是问题的解决方案。&nbsp; &nbsp; <?php&nbsp; &nbsp; $sample = array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "term_1_mid" => array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"English" => 56,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Mathematics" => 34,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Creative Arts" => 87),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "terrm_1_end" => array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"English" => 67,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Mathematics" => 59,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Creative Arts" => 95)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp;# Initializing array to store the result&nbsp; &nbsp; &nbsp;$output_array = array();&nbsp; &nbsp; &nbsp;# Loop for adding the values&nbsp; &nbsp; &nbsp;foreach($sample as $sample_key => $sample_value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foreach ($sample_value as $key => $value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$output_array[$key] += $value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;# To check the data in array&nbsp; &nbsp; &nbsp;foreach($output_array as $key => $value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# used br tag only to show the each values in each line&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;echo $key . " => ". $value . "<br>";&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;?>输出 :English => 123Mathematics => 93Creative Arts => 182

哈士奇WWW

这是一个演示。$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){&nbsp; &nbsp; foreach($termname as $sub=>$mark){&nbsp; &nbsp; &nbsp; &nbsp; if(!isset($arrSum[$sub])){$arrSum[$sub] = 0;}&nbsp; &nbsp; &nbsp; &nbsp; $arrSum[$sub] += $mark;&nbsp; &nbsp; }}print_r($arrSum);
随时随地看视频慕课网APP
我要回答