Php Array Zipper - add two arrays by key value

103 views Asked by At

I am trying to do this as efficiently as possible.

I have multiple arrays:

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,
    ]
]

I want to add these arrays together with a desired output of Year/Month Totals:

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

I wanted to avoid mulitple foreach loops and figured there would be a better solution with array_map, array_walk or anything else. Anyone got ideas?

Thanks

2

There are 2 answers

3
Werner On BEST ANSWER

Here's a single foreach. But a triple ternary 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;
  }
}
1
Andreas On

I believe you need to use some kind of foreach to do this effective.

I create a new array with all arrays in it and loop the subarrays of it to sum the values.

// 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