我有一个由日期值(第二个字段)组成的多维数组。 我正在尝试使用以下逻辑按日期的降序对整个数组进行排序:
$cars = array
(
array("Volvo","09/09/2016 10:39:50 am",18),
array("BMW","09/09/2016 10:38:46 am",13),
array("Saab","09/09/2017 10:38:49 am",200),
array("Saab","09/09/2016 10:38:49 am",2),
);
echo $cars[0][0]." ".$cars[0][1]." ".$cars[0][2];
echo "<br>";
echo $cars[1][0]." ".$cars[1][1]." ".$cars[1][2];
echo "<br>";
echo $cars[2][0]." ".$cars[2][1]." ".$cars[2][2];
echo "<br>";
echo $cars[3][0]." ".$cars[3][1]." ".$cars[3][2];
echo "<br>";
usort($cars, "cmp");
function cmp($a, $b){
return strcmp($b[1], $a[1]);
}
echo "<br>";
echo $cars[0][0]." ".$cars[0][1]." ".$cars[0][2];
echo "<br>";
echo $cars[1][0]." ".$cars[1][1]." ".$cars[1][2];
echo "<br>";
echo $cars[2][0]." ".$cars[2][1]." ".$cars[2][2];
echo "<br>";
echo $cars[3][0]." ".$cars[3][1]." ".$cars[3][2];
echo "<br>";
但是上面给出了以下输出:
之前:----------
Volvo 09/09/2016 10:39:50 am 18
BMW 09/09/2016 10:38:46 am 13
Saab 09/09/2010 10:38:49 am 200
Saab 09/08/2016 10:38:49 am 2
之后:----------
Volvo 09/09/2016 10:39:50 am 18
BMW 09/09/2016 10:38:46 am 13
Saab 09/09/2010 10:38:49 am 200
Saab 09/08/2016 10:38:49 am 2
我期待的输出是:
Volvo 09/09/2016 10:39:50 am 18
BMW 09/09/2016 10:38:46 am 13
Saab 09/08/2016 10:38:49 am 2
Saab 09/09/2010 10:38:49 am 200
任何帮助都非常有用
答案 0 :(得分:1)
使用usort()
和strtotime()
来比较日期
usort($cars, function($a, $b){
return strtotime($a[1]) < strtotime($b[1]);
});
答案 1 :(得分:1)
在PHP 7中
{{1}}