我有以下php array
对象:
"requests": [
{
"id": 111,
"time: 123123123,
"data": "testc"
},
{
"id": 200 ,
"time: 433123123,
"data": "testb"
},
{
"id": 300 ,
"time: 33123123,
"data": "testb"
}
]
我只想按requests->time
排序。怎么做?
我不想按id
排序。所有数据都应按time ASC
排序。
答案 0 :(得分:2)
假设您在$requests
变量中包含该数组,则以下内容应该可以正常工作
<?php
function cmp($a, $b)
{
return strcmp($a["time"],$b["time"]);
}
usort($requests, "cmp");
//print for test
while (list($key, $value) = each($requests)) {
echo "\$requests[$key]: " . $value["time"] . "\n";
}
?>
答案 1 :(得分:1)
您必须使用自己的排序方法usort()
解决方案:
<?php
function sortByTimeASC($a, $b)
{
if ($a->time == $b->time) {
return 0;
}
return ($a->time < $b->time) ? -1 : 1;
}
$a = json_decode('[{"id": 111,"time": 123123123,"data": "testc"},{ "id":200 ,"time":433123123,"data":"testb"},{"id":300,"time":33123123,"data":"testb"}]');
usort($a, "sortByTimeASC");
print_r($a);
?>