简体   繁体   中英

Php multidimensional array filter and sum

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.

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

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'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM