如何對多維關聯數組的值求和?我的數組如下:$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 關注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消