开发者

Sort array by keys which are in Ymd format with no delimiting characters [duplicate]

This question already has answers here: 开发者_开发问答 How to sort an array by keys in an ascending direction? (3 answers) Closed 7 months ago.

I have an array with keys as date in this format.

$arr = array(

    "20110805" => "2",
    "20100703" => "5",
    "20110413" => "3",
    "20100805" => "4",
    "20100728" => "6",
    "20090416" => "7",
    "20080424" => "8",
    "20110819" => "1",  
);

How can I sort this array by key?


With the dates in that format, an alphabetical comparison will work just fine. Use the PHP function ksort.

ksort($arr);


A slightly more complex solution, which nonetheless works for almost any date format, is based on the uksort function.

First we define a callback function that compares two dates (comparator):

function compare_date_keys($dt1, $dt2) {
    return strtotime($dt1) - strtotime($dt2);
}

Now we can use the just defined function as the second parameter in uksort, as in the example below:

uksort($arr, "compare_date_keys");

As a result the function will treat the key as a date and sort the array in ascending order (less recent first).

Note that we can easily tweak the comparator to support different use cases. For example, sorting by date descending (most recent first) can be accomplished by simply replacing the function's return expression with the following:

return strtotime($dt2) - strtotime($dt1);


Just this single line of code:

ksort($arr);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜