我想按日期时间按降序对数组进行排序。这是示例数组:
<?php
$var1 = "2016-12-30 12:30:59";
$var2 = "2015-11-21 11:30:59";
$var3 = "2017-01-15 10:30:59";
$a = array($var1, $var2, $var3);
function compare_func($a, $b) {
// CONVERT $a AND $b to DATE AND TIME using strtotime() function
$t1 = strtotime($a[0]);
$t2 = strtotime($a[1]);
return ($t2 - $t1);
}
usort($a, "compare_func");
var_export($a);
?>
我得到的输出是:
array (
0 => '2017-01-15 10:30:59',
1 => '2015-11-21 11:30:59',
2 => '2016-12-30 12:30:59',
)
答案 0 :(得分:2)
您可以直接比较字符串。
function compare_func($a, $b) {
return ($a > $b);
}
答案 1 :(得分:0)
试试这个:
<?php
$var1 = "2016-12-30 12:30:59";
$var2 = "2015-11-21 11:30:59";
$var3 = "2017-01-15 10:30:59";
$arr = array($var1, $var2, $var3);
function date_sort($a, $b) {
return strtotime($b) - strtotime($a);
}
usort($arr, "date_sort");
print_r($arr)
?>
OUTPUT 按降序排列
Array
(
[0] => 2017-01-15 10:30:59
[1] => 2016-12-30 12:30:59
[2] => 2015-11-21 11:30:59
)