如何找到多维关联数组的和?

你好 :

如何对多维关联数组的值求和?

我的数组如下:

$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

我如何获得所需的结果,如下所示将category1和category2值相加:

"2019-12-31" => 30
"2020-01-31" => 300
"2020-02-28" => 3000
巴马尔:

而不是嵌套循环,请使用array_sum()array_column()

foreach ($testarray[0] as $date => $results) {
    $sums[$date] = array_sum(array_column($results, 'total'));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章