简单的日期明智排序数组不工作

时间:2015-08-12 13:34:53

标签: php arrays sorting date

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

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

我正在尝试根据date.transaction日期对数组进行排序或分组应该是一个意味着数组中没有重复的事务条目。我希望这个数组也应该按日期排序。应该首先考虑2015-01-01如果日期可用,则在2015-01-01旁边进行2015-02-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"}} 

您可以在此链接中查看此arrray http://jsonviewer.stack.hu/

1 个答案:

答案 0 :(得分:0)

尝试使用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