gpt4 book ai didi

php - 简单的日期明智排序数组不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 21:57:32 25 4
gpt4 key购买 nike

这是我的数组。(这个数组是例子)

Array(
[0] => Array
(
[amt] => 50.00
[transaction_date] => 2015-01-01
)
[1] => Array
(
[amt] => 0.00
[transaction_date] => 2015-02-01
)

[2] => Array
(
[amt] => 60.00
[transaction_date] => 2015-01-01
)
)

我正在尝试根据日期对数组进行排序或分组。交易日期应该是一个意味着数组中没有重复的交易条目。我希望这个数组也应该按日期排序。意味着 2015-01-01 应该首先和 2015-02-01 在 2015-01-01 之后,如果日期可用,依此类推。

我想要如下的新数组

Array(
[0] => Array
(
[amt] => 110.00
[transaction_date] => 2015-01-01
)

[1] => Array
(
[amt] => 0.00
[transaction_date] => 2015-02-01
)

)

2015-01-01 此日期在数组中出现 2 次,每次重复时应添加 2 个不同的金额。数量应该是110

我试过了

$result = array();
foreach ($output as $key => $value) {
$hash = $value['transaction_date'];
if (isset($result[$hash])) {
$result[$hash]['amt'] += $value['amt'];
$result[$hash]['transaction_date'] = $value['transaction_date'];
} else {
$result[$hash]['amt'] = $value['amt'];
$result[$hash]['transaction_date'] = $value['transaction_date'];
}
}
print_r(array_values($result));

这是我实际的json编码结果

{"2015-07-18":{"amt":50,"transaction_date":"2015-07-18"},"2015-05-28":{"amt":"450.00","transaction_date":"2015-05-28"},"2015-06-02":{"amt":"200.00","transaction_date":"2015-06-02"},"2015-06-18":{"amt":"12610.00","transaction_date":"2015-06-18"},"2015-06-23":{"amt":"0.00","transaction_date":"2015-06-23"},"2015-06-24":{"amt":"603.00","transaction_date":"2015-06-24"},"2015-07-14":{"amt":"0.00","transaction_date":"2015-07-14"},"2015-07-16":{"amt":"0.00","transaction_date":"2015-07-16"},"2015-07-17":{"amt":"0.00","transaction_date":"2015-07-17"}} 

你可以在这个链接中查看这个数组 http://jsonviewer.stack.hu/

最佳答案

尝试简单地使用 usort 作为

$result = array();
foreach ($output as $key => $value) {
$hash = $value['transaction_date'];
if (isset($result[$hash])) {
$result[$hash]['amt'] += $value['amt'];
$result[$hash]['transaction_date'] = $value['transaction_date'];
} else {
$result[$hash]['amt'] = $value['amt'];
$result[$hash]['transaction_date'] = $value['transaction_date'];
}
}

uasort(array_values($result),function($a,$b){
return $a['transaction_date'] - $b['transaction_date'];
});
print_r(array_values($result));

Demo

关于php - 简单的日期明智排序数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966796/

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