Php Array Zipper - 按键值添加两个数组

Php Array Zipper - add two arrays by key value

我正在尝试尽可能高效地执行此操作。

我有多个数组:

array1 = [
 "2018" => 
    [
        "JAN" => 100,
        "FEB" => 200,
        "MAR" => 300,
        "APR" => 400
    ]
]

array2 = [
 "2018" => 
    [
        "FEB" => 200,
        "MAR" => 300,
        "APR" => 400,
        "MAY" => 200,
    ]
]

array3 = [
 "2018" => 
    [
        "MAY" => 200,
        "JUN" => 100,
        "JUL" => 300,
        "AUG" => 400,
    ]
]

我想将这些数组与所需的输出相加 Year/Month 总计:

sumArray = [
     "2018" => 
        [
            "JAN" => 100,
            "FEB" => 400,
            "MAR" => 600,
            "APR" => 800
            "MAY" => 400,
            "JUN" => 100,
            "JUL" => 300,
            "AUG" => 400,
        ]
    ]

我想避免多个 foreach 循环,并认为 array_map、array_walk 或其他任何东西都会有更好的解决方案。有人有想法吗?

谢谢

这是一个 foreach。但是三重三元 ifs:

$monthCodes = array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
foreach($monthCodes as $key => $monthCode){
  $add = 0;
  $add += ( isset($array1["2018"][$monthCode]) ) ?  $array1["2018"][$monthCode] : 0;
  $add += ( isset($array2["2018"][$monthCode]) ) ?  $array2["2018"][$monthCode] : 0;
  $add += ( isset($array3["2018"][$monthCode]) ) ?  $array3["2018"][$monthCode] : 0;
  if($add <> 0){
    $sumArray["2018"][$monthCode] = $add;
  }
}

我相信您需要使用某种 foreach 才能有效地做到这一点。

我创建了一个包含所有数组的新数组,并循环它的子数组以对值求和。

// Add arrays that needs to be summed in the line below
$new = array_merge_recursive([$array1], [$array2], [$array3]);
foreach($new as $arr){
    foreach($arr as $year => $sub){
        foreach($sub as $month => $val){
            if(!isset($res[$year][$month])) $res[$year][$month] =0;
            $res[$year][$month] += $val;
        }
    }
}
var_dump($res);

https://3v4l.org/WHdDJi