按日期排序数组php

时间:2017-07-07 10:24:57

标签: php arrays sorting php-5.3

数组键是日期,并希望按照Asending顺序按日期排序数组。以下是数组:

Array
(
    [07/14/2017] => Array
        (
            [ID] => 5442
            [post_content] => Test1
            [post_title] => Testevents1
        )

    [01/11/2017] => Array
        (
            [ID] => 5443
            [post_content] => Test2
            [post_title] => Testevents2
        )
)

2 个答案:

答案 0 :(得分:2)

您可以使用uksort来执行此操作:

uksort($arr, function ($a, $b) {
    $t1 = strtotime($a);
    $t2 = strtotime($b);
    if ($t1 == $t2) {
        return 0;
    }
    return ($t1 > $t2) ? 1 : -1;
});

答案 1 :(得分:0)

您可以使用uksort

uksort - 使用用户定义的比较函数按键对数组进行排序

function cmp($keyA, $keyB)
{
    // Your date parsing and comparison

    // The comparison function must return an integer less than, equal to, 
    // or greater than zero if the first argument is considered to be respectively 
    // less than, equal to, or greater than the second. 
    // Note that before PHP 7.0.0 this integer had to be in the range 
    // from -2147483648 to 2147483647.
}

uksort($arr, "cmp")