按日期排序数组 php
Sort array by date php
数组键是日期,想按日期升序排列数组。以下是数组:
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
)
)
您可以使用 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")
您可以使用 uksort
来做到这一点:
uksort($arr, function ($a, $b) {
$t1 = strtotime($a);
$t2 = strtotime($b);
if ($t1 == $t2) {
return 0;
}
return ($t1 > $t2) ? 1 : -1;
});
数组键是日期,想按日期升序排列数组。以下是数组:
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
)
)
您可以使用 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")
您可以使用 uksort
来做到这一点:
uksort($arr, function ($a, $b) {
$t1 = strtotime($a);
$t2 = strtotime($b);
if ($t1 == $t2) {
return 0;
}
return ($t1 > $t2) ? 1 : -1;
});