我有一个问题,我有这个数组:
Array
(
[0] => Array
(
[date] => 2015-07-07
[nb] => 12
)
[1] => Array
(
[date] => 2015-07-10
[nb] => 6
)
[2] => Array
(
[date] => 2015-07-07
[nb] => 8
)
[3] => Array
(
[date] => 2015-07-09
[nb] => 48
)
[4] => Array
(
[date] => 2015-07-09
[nb] => 42
)
}
但我想获得这个:
Array
(
[0] => Array
(
[date] => 2015-07-07
[nb] => 20
)
[1] => Array
(
[date] => 2015-07-09
[nb] => 90
)
[2] => Array
(
[date] => 2015-07-10
[nb] => 6
)
}
这个想法是,如果在数组中存在多个日期[nb]必须加起来。
我试过这样:
foreach($aTotalRows as $k=>$row){
if($row[$k]['date'] == $row[$k+1]['date']){
$row[$k]['nb'] = $row[$k]['nb'] + $row[$k+1]['nb']
}
}
但不能解决这个问题,你能帮帮我吗? Thx提前
答案 0 :(得分:7)
不,这只有在您按日期排序时才有效....尝试构建类似的内容:
$aggregateArray = array();
foreach($aTotalRows as $row) {
if(!array_key_exists($row['date'], $aggregateArray) {
$aggregateArray[$row['date']] = 0;
}
$aggregateArray[$row['date']] += $row['nb']
}
会给你类似的东西:
Array(
['2015-07-07'] => 20
['2015-07-10'] => 90
['2015-07-11'] => 6
)
然后你可以在必要时进行重组
答案 1 :(得分:2)
如果要处理未排序的数组,则必须更改类似的代码,
$input = array(
array('date' => '2015-07-07', 'nb' => 12),
array('date' => '2015-07-10', 'nb' => 6),
array('date' => '2015-07-07', 'nb' => 8),
array('date' => '2015-07-09', 'nb' => 48),
array('date' => '2015-07-09', 'nb' => 42)
);
$required = array();
array_walk($input, function($v) use(&$required){
if(!isset($required[$v['date']])){ $required[$v['date']] = 0; }
$required[$v['date']] += $v['nb'];
});
$final = array_map(function($v, $k){
return array('date'=>$k, 'nb'=>$v);
}, $required, array_keys($required));
转储$required
array (size=3)
'2015-07-07' => int 20
'2015-07-10' => int 6
'2015-07-09' => int 90
转储$final
array (size=3)
0 =>
array (size=2)
'date' => string '2015-07-07' (length=10)
'nb' => int 20
1 =>
array (size=2)
'date' => string '2015-07-10' (length=10)
'nb' => int 6
2 =>
array (size=2)
'date' => string '2015-07-09' (length=10)
'nb' => int 90
答案 2 :(得分:2)
你可以在一条路上做到这一点
TupleElement