我有一个多维数组,形式为;
Array
(
[0] => Array
(
[DATE] => 05-19-2011
[PERSON] => Bob Hope
[ITEM] => Holiday
[DURATION] => 04:00
)
[1] => Array
(
[DATE] => 05-19-2011
[PERSON] => Bob Hope
[ITEM] => Work
[DURATION] => 05:00
)
[2] => Array
(
[DATE] => 05-19-2011
[PERSON] => Bob Hope
[ITEM] => Holiday
[DURATION] => 06:00
)
[3] => Array
(
[DATE] => 05-19-2011
[PERSON] => Bob Hope
[ITEM] => Work
[DURATION] => 05:00
)
[4] => Array
(
[DATE] => 05-19-2011
[PERSON] => Joe Bloggs
[ITEM] => Holiday
[DURATION] => 02:00
)
[5] => Array
(
[DATE] => 05-19-2011
[PERSON] => Joe Bloggs
[ITEM] => Work
[DURATION] => 03:00
)
[6] => Array
(
[DATE] => 05-19-2011
[PERSON] => Joe Bloggs
[ITEM] => Holiday
[DURATION] => 03:00
)
[7] => Array
(
[DATE] => 05-19-2011
[PERSON] => Joe Bloggs
[ITEM] => Work
[DURATION] => 02:00
)
)
并希望整理结果,为每个人总结假期和工作,以便我可以输出形式的东西;
Array
(
[0] => Array
(
[DATE] => 05-19-2011
[PERSON] => Bob Hope
[ITEM] => Holiday
[DURATION] => 10:00
)
[1] => Array
(
[DATE] => 05-19-2011
[PERSON] => Bob Hope
[ITEM] => Work
[DURATION] => 10:00
)
[2] => Array
(
[DATE] => 05-19-2011
[PERSON] => Joe Bloggs
[ITEM] => Holiday
[DURATION] => 05:00
)
[3] => Array
(
[DATE] => 05-19-2011
[PERSON] => Joe Bloggs
[ITEM] => Work
[DURATION] => 05:00
)
)
有什么想法吗?任何和所有帮助表示赞赏。
答案 0 :(得分:2)
数据来自哪里?通常,此类数据来自数据库,在这种情况下,以下语句将完全符合您的要求:
SELECT
SUM(DURATION),
ITEM,
PERSON
FROM
yourtable
GROUP BY
PERSON,
ITEM;
编辑:如果你想按项目对它们进行分组,只需声明它。
答案 1 :(得分:1)
好吧,很多foreach,但你基本上是在一个单独的结构中添加值,并重新排列结果数组:
$items = array(
0 => Array(
'DATE' => '05-19-2011',
'PERSON' => 'Bob Hope',
'ITEM' => 'Holiday',
'DURATION' => '10:00',
),
1 => Array(
'DATE' => '05-19-2011',
'PERSON' => 'Bob Hope',
'ITEM' => 'Work',
'DURATION' => '10:00',
),
2 => Array(
'DATE' => '05-19-2011',
'PERSON' => 'Joe Bloggs',
'ITEM' => 'Holiday',
'DURATION' => '05:00',
),
3 => Array(
'DATE' => '05-19-2011',
'PERSON' => 'Joe Bloggs',
'ITEM' => 'Work',
'DURATION' => '05:00',
),
);
foreach($items as $key=>$value){
$item = $value['ITEM'];
$out[$value['PERSON']][$value['DATE']][$value['ITEM']] += $value['DURATION'];
}
foreach($out as $person=>$data){
foreach($data as $date=>$items){
foreach($items as $item=>$duration){
$result[] = array(
'PERSON'=>$person,
'DATE'=>$date,
'ITEM'=>$item,
'DURATION'=>$duration,
);
}
}
}
print_r($result);
答案 2 :(得分:0)
答案 3 :(得分:0)
如果你真的想用PHP解决这个问题,我建议不要嵌套太多的循环。这是我的解决方案(看起来很丑陋。):
$result = array();
foreach ($data as $row) {
$key = $row['PERSON'] . '|' . $row['ITEM'];
$tmp = explode(':', $row['DURATION']);
$row['DURATION'] = $tmp[0] * 60 + $tmp[1];
if (!isset($result[$key])) {
$result[$key] = $row;
} else {
$result[$key]['DURATION'] += $row['DURATION'];
}
}
$result = array_map(function($v) {
$v['DURATION'] = strftime('%M:%S', $v['DURATION']);
return $v;
}, array_values($result));