我有如下所示的数组,如何对日期和时间降序组合的数据进行排序?
$manifest = array(
array("date"=>2019-02-21,"time"=>04:49:54,"desc"=>"arrived in indonesia"),
array("date"=>2019-02-25,"time"=>04:02:21,"desc"=>"arrived in soppeng"),
array("date"=>2019-02-22,"time"=>01:42:51,"desc"=>"arrived in makassar"),
array("date"=>2019-02-22,"time"=>02:42:51,"desc"=>"arrived in makassar gateway"),
);
预期结果:
$manifest = array(
array("date"=>2019-02-25,"time"=>04:02:21,"desc"=>"arrived in soppeng"),
array("date"=>2019-02-22,"time"=>02:42:51,"desc"=>"arrived in makassar gateway"),
array("date"=>2019-02-22,"time"=>01:42:51,"desc"=>"arrived in makassar"),
array("date"=>2019-02-21,"time"=>04:49:54,"desc"=>"arrived in indonesia")
);
感谢帮助
答案 0 :(得分:2)
$arr = $manifest;
usort($arr, function($a, $b) {
$ad = new DateTime($a['date'] ." ". $a['time']);
$bd = new DateTime($b['date']." ". $a['time']);
if ($ad == $bd) {
return 0;
}
return $ad < $bd ? 1 : -1;
});
答案 1 :(得分:1)
您可以使用rsort()
来对数组进行降序排序。
<?php
$manifest = array(
array("date"=>"2019-02-21","time"=>"04:49:54","desc"=>"arrived in indonesia"),
array("date"=>"2019-02-25","time"=>"04:02:21","desc"=>"arrived in soppeng"),
array("date"=>"2019-02-22","time"=>"01:42:51","desc"=>"arrived in makassar"),
array("date"=>"2019-02-22","time"=>"02:42:51","desc"=>"arrived in makassar gateway")
);
rsort($manifest);
echo '<pre>';print_r($manifest);echo '</pre>';
?>
输出:
Array
(
[0] => Array
(
[date] => 2019-02-25
[time] => 04:02:21
[desc] => arrived in soppeng
)
[1] => Array
(
[date] => 2019-02-22
[time] => 02:42:51
[desc] => arrived in makassar gateway
)
[2] => Array
(
[date] => 2019-02-22
[time] => 01:42:51
[desc] => arrived in makassar
)
[3] => Array
(
[date] => 2019-02-21
[time] => 04:49:54
[desc] => arrived in indonesia
)
)
答案 2 :(得分:1)
array-multisort怎么样?
array_multisort(array_column($manifest, 'date'), SORT_DESC, array_column($manifest, 'time'), SORT_DESC, $manifest);
就这么简单
答案 3 :(得分:1)
我解决了自己,我在使用
usort($manifest,function($a,$b){
return strtotime($b['date']." ".$b['time']) - strtotime($a['date']." ".$a['time']);
});
感谢所有人的帮助。