我在以下结构中的数组中包含数据:
[8] => Array
(
[totalTonne] => 660
[wasteHierarchy] => Recycling
[completionDate] => 2014-05-20
)
[9] => Array
(
[totalTonne] => 860
[wasteHierarchy] => Recycling
[completionDate] => 2014-05-21
)
[10] => Array
(
[totalTonne] => 520
[wasteHierarchy] => Disposal (Landfill)
[completionDate] => 2014-06-23
)
[11] => Array
(
[totalTonne] => 420
[wasteHierarchy] => Disposal (Landfill)
[completionDate] => 2014-06-24
)
我想要的是拥有这样的结构:
[Disposal (Landfill)] => Array
(
[May 14] => 11180
)
[Energy Recovery] => Array
(
[Jun 14] => 16320
[Aug 14] => 22940
[Nov 14] => 21820
)
[Recycling] => Array
(
[Jul 14] => 18660
[Sep 14] => 22480
[Oct 14] => 17800
[Dec 14] => 19160
[Jan 15] => 5520
)
因此,每个wasteHierarchy
都会自行分组,然后日期按月和年分组,并将累积的totalTonne
值添加到其中。
到目前为止,我的PHP代码如下:
$whmOutput = Array();
foreach($wasteHierMon as $whm) {
$dateChanged = date("M y", strtotime($whm['completionDate']));
$whmOutput_element = &$whmOutput[$dateChanged];
$whmOutput_element['wasteHierarchy'] = $whm['wasteHierarchy'];
$whmOutput_element['completionDate'] = $dateChanged;
!isset($whmOutput_element['totalUom']) && $whmOutput_element['totalUom'] = 0;
$whmOutput_element['totalUom'] += $whm['totalTonne'];
}
$newWHM = array();
foreach($whmOutput as $whm) {
$dateChanged = $whm['completionDate'];
$wasteHierarchy = $whm['wasteHierarchy'];
$totalUom = +$whm['totalUom'];
$newWHM[$wasteHierarchy][$dateChanged] = $totalUom;
}
但是,该代码无法正常完成工作。虽然它创建了我追求的结构,但它没有正确地重新排列数据。它没有正确地对日期进行分组,因此,totalTonne
值不正确。
如何修改代码才能实现此目的?
答案 0 :(得分:1)
这样的事情应该有效
$whmOutput = array();
foreach ($wasteHierMon as $whm) {
$dateChanged = date("M y", strtotime($whm['completionDate']));
// if not defined, define with value zero
if (!isset($whmOutput[$whm['wasteHierarchy']][$dateChanged])) {
$whmOutput[$whm['wasteHierarchy']][$dateChanged] = 0;
}
// addition will always work now
$whmOutput[$whm['wasteHierarchy']][$dateChanged] += $whm['totalTonne'];
}
输出:
Array
(
[Recycling] => Array
(
[May 14] => 1520
)
[Disposal (Landfill)] => Array
(
[Jun 14] => 940
)
)
的 DEMO 强>