php - 以日期为关键字对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7134776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php - Sort array with date as key
提问by bharath
Hi 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. Thank you.
如何按键对这个数组进行排序。谢谢你。
回答by coyotebush
回答by Marian Galik
Just this single line of code:
就这一行代码:
ksort($arr);
回答by Sal Borrelli
A slightly more complex solution, which nonetheless works for almost any date format, is based on the uksortfunction.
一个稍微复杂一点的解决方案是基于uksort函数,但它几乎适用于任何日期格式。
First we define a callback functionthat compares two dates (comparator):
首先我们定义一个比较两个日期的回调函数(comparator):
function compare_date_keys($dt1, $dt2) {
$tm1 = strtotime($dt1);
$tm2 = strtotime($dt2);
return ($tm1 < $tm2) ? -1 : (($tm1 > $tm2) ? 1 : 0);
}
Now we can use the just defined function as the second parameter in uksort, as in the example below:
现在我们可以使用刚刚定义的函数作为 uksort 中的第二个参数,如下例所示:
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 ($tm1 < $tm2) ? 1 : (($tm1 > $tm2) ? -1 : 0);