Reputation: 278
I have following php array
object:
"requests": [
{
"id": 111,
"time: 123123123,
"data": "testc"
},
{
"id": 200 ,
"time: 433123123,
"data": "testb"
},
{
"id": 300 ,
"time: 33123123,
"data": "testb"
}
]
I want to sort it by requests->time
only. How to do it?
I don't want sort by id
. All data should be sort as per time ASC
.
Upvotes: 0
Views: 64
Reputation: 176
You have to use your own sort method with usort()
Solution :
<?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);
?>
Upvotes: 1
Reputation: 2435
supposing you have that array in a $requests
variable, the following should work
<?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";
}
?>
Upvotes: 2