Q:

Sum of elements in multidimensional array

I have the 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 I expect the 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 so far?
$monthlyData = array();

foreach ($dailyData as $day)
{
    $key = date('M y', strtotime($day['date']));

    if (!isset($monthlyData[$key]))
    {
        $monthlyData[$key] = $day;
        continue;
    }

    foreach ($day as $metric => $value)
    {
        if(!empty($value)) 
        {
            $monthlyData[$key][$metric] += $value;
        }
    }
}

Well, I know that we can use good ol' foreach (with recursive calls) in order to get the right result, but I'm looking for some more elegant solution.

A:

You really just need one more condition and loop for this specific example.
foreach ($day as $metric => $value)
{
    /* Added Condition */
    if(is_array($value))
    {
        foreach($value as $nestedMetric => $nestedValue) {
            $monthlyData[$key][$metric][$nestedMetric] += $nestedValue;
        }
    }
    elseif(!empty($value)) 
    {
        $monthlyData[$key][$metric] += $value;
    }
}

However, I'd probably do it differently by handling the calculation based on the metric, not just treating every metric dynamically.

