Php multidimensional array filter and sum

79 views Asked by At

i've a multidimensional array like this one:

['2021-04-01'=>
      ['hb' => 35, 'fb' => 40, 'ai' => 50],
'2021-04-02'=>
      ['hb' => 35, 'fb' => 40, 'ai' => 50],
'2021-04-03'=>
      ['hb' => 40, 'ai' => 55],
'2021-04-04'=>
      ['hb' => 40, 'fb' => 45, 'ai' => 55],
'2021-04-05'=>
      ['hb' => 35, 'ai' => 50]]

I'd like to receive an array like this one:

['hb'=>185,'ai'=>260]

Basically i've to sum the price of every single treatment (hb=half-board, fb=full board, ai=all inclusive) only if the treatment is present in every element of the array.

2

There are 2 answers

0
jspit On

Short solution with array_reduce().

$sum = array_reduce($arr ,function($carry,$val){
    return ['hb'=>$carry['hb']+$val['hb'],'ai'=>$carry['ai']+$val['ai']];
  },
  ['hb'=>0,'ai'=>0]
);

$arr is your input-array, $sum the result.

More understandable what array_reduce makes is a simple loop with foreach.

$sum = ['hb' => 0, 'ai' => 0];
foreach($arr as $row){
  $sum['hb'] += $row['hb'];
  $sum['ai'] += $row['ai'];
}
0
Filip Kováč On

Basically the foreach loop is propably the best option. Although you can use array_sum function after array_map. Example for foreach:

$ret = []
foreach ($input_array as $second_array) {
     foreach ($second_array as $key => $value) {
         if (!isset($ret[$key]))
              $ret[$key] = 0;
         $ret[$key] += $value
     }
}