如何对多维关联数组的值求和?我的数组如下:$testarray=[];$testarray[]=[ "2019-12-31" => [ "category1" => [ "total" => "10" ], "category2" => [ "total" => "20" ], ], "2020-01-31" => [ "category1" => [ "total" => "100" ], "category2" => [ "total" => "200" ], ], "2020-02-28" => [ "category1" => [ "total" => "1000" ], "category2" => [ "total" => "2000" ] ], ];我尝试了以下方法:foreach($testarray[0] as $Offset=>$ArrayOfResults){ foreach($ArrayOfResults as $ResultOffset=>$Result){ $total+= $Result["total"]; } $sums[$Offset]=$total;}结果是:"2019-12-31" => 30"2020-01-31" => 330"2020-02-28" => 3330如何获得所需的结果,如下将类别 1 和类别 2 值相加:"2019-12-31" => 30"2020-01-31" => 300"2020-02-28" => 3000
2 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
array_sum()
使用and代替嵌套循环array_column()
。
foreach ($testarray[0] as $date => $results) { $sums[$date] = array_sum(array_column($results, 'total'));
慕娘9325324
TA贡献1783条经验 获得超4个赞
您只需要重置$total每次迭代:
foreach($testarray[0] as $Offset=>$ArrayOfResults){
$total = 0;
foreach($ArrayOfResults as $ResultOffset=>$Result){
$total+= $Result["total"];
}
$sums[$Offset]=$total;
}
- 2 回答
- 0 关注
- 120 浏览
添加回答
举报
0/150
提交
取消