gpt4 book ai didi

php - 如果具有相同的日期,则计算元素的总和

转载 作者:行者123 更新时间:2023-12-04 15:48:00 26 4
gpt4 key购买 nike

我有一个问题,我有这个数组:

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']
}
}

但这个解决方案不起作用,你能帮帮我吗?提前致谢

最佳答案

不,这只有在你先按日期排序时才有效......尝试构建类似的东西:

$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
)

然后你可以根据需要重组它

关于php - 如果具有相同的日期,则计算元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31402234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com