phparraysloopsarray-maparray-walk

Php Array Zipper - add two arrays by key value


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


Solution

  • 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;
      }
    }