-1

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
    Does this answer your question? [Sum values of multidimensional array by key without loop](https://stackoverflow.com/questions/16138395/sum-values-of-multidimensional-array-by-key-without-loop) – El_Vanja Apr 20 '21 at 17:29

2 Answers2

0

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
     }
}     
Filip Kováč
  • 499
  • 8
  • 15
0

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'];
}
jspit
  • 7,276
  • 1
  • 9
  • 17