我有一个数组。现在我想按date.how排序这个数组?
我的数组
$ details = $ this-> api_model-> testw()
这里的mysql查询在$ details中返回结果数组。
我想将数组排序为日期,然后想要显示输出json
计算我的输出后显示在json中。
"details":[
{
"id":"2",
"score":"1256",
"user_id":"5",
"date":"2014-02-05 00:00:00",
},
{
"id":"3",
"score":"100",
"user_id":"6",
"date":"2014-03-08 00:00:00",
},
{
"id":"4",
"score":"123",
"user_id":"7",
"date":"2014-03-04 00:00:00",
},
]
我正在尝试使用ksort但不能正常工作
答案 0 :(得分:4)
使用usort。该函数将数组中的日期字段转换为可以轻松相互比较的unix时间戳。
<?php
$arr = array(
array( "id" => 2, "date" => "2014-02-05 00:00:00"),
array( "id" => 3, "date" => "2013-02-05 00:00:00"),
array( "id" => 4, "date" => "2012-02-05 00:00:00"),
array( "id" => 5, "date" => "2011-02-05 00:00:00"),
array( "id" => 6, "date" => "2012-02-05 00:00:00"),
array( "id" => 7, "date" => "2012-04-05 00:00:00"),
array( "id" => 8, "date" => "2018-02-05 00:00:00"));
usort($arr,function($a,$b)
{
$a = strtotime($a['date']);
$b = strtotime($b['date']);
//return $a - $b; //is possible too, but harder to understand
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
);
print_r($arr);