php - Sum of elements in multidimensional array -


i have following input:

$data = array(     0 => array(         'date' => '2014-01-01',         'sales' => 1,         'price' => array(             'usd' => 1,             'eur' => 100         )     ),     1 => array(         'date' => '2014-01-05',         'sales' => 1,         'price' => array(             'usd' => 1,             'eur' => 100,             'gbp' => 500         )     ),     2 => array(         'date' => '2016-03-27',         'sales' => 5,         'age' => 50     ),     3 => array(          'date' => '2016-03-28',         'sales' => 10     ) ); 

and expect following output:

$final = array(     'march 2016' => array(         'sales' => 15     ),     'january 2014' => array(         'sales' => 2,         'price' => array(             'usd' => 2,             'eur' => 200,             'gbp' => 500         )     ) ); 

what i've done far?

$monthlydata = array();  foreach ($dailydata $day) {     $key = date('m y', strtotime($day['date']));      if (!isset($monthlydata[$key]))     {         $monthlydata[$key] = $day;         continue;     }      foreach ($day $metric => $value)     {         if(!empty($value))          {             $monthlydata[$key][$metric] += $value;         }     } } 

well, know can use ol' foreach (with recursive calls) in order right result, i'm looking more elegant solution.

you need 1 more condition , loop specific example.

foreach ($day $metric => $value) {     /* added condition */     if(is_array($value))     {         foreach($value $nestedmetric => $nestedvalue) {             $monthlydata[$key][$metric][$nestedmetric] += $nestedvalue;         }     }     elseif(!empty($value))      {         $monthlydata[$key][$metric] += $value;     } } 

however, i'd differently handling calculation based on metric, not treating every metric dynamically.


Comments