我有以下输入:
$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
)
);
我期待以下输出:
$final = array(
'March 2016' => array(
'sales' => 15
),
'January 2014' => array(
'sales' => 2,
'price' => array(
'usd' => 2,
'eur' => 200,
'gbp' => 500
)
)
);
到目前为止我做了什么?
$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;
}
}
}
嗯,我知道我们可以使用好的'foreach
(使用递归调用)来获得正确的结果,但我正在寻找一些更优雅的解决方案。