0

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.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
user3264863
  • 278
  • 4
  • 15

2 Answers2

2

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";
    }

?>
ddb
  • 2,423
  • 7
  • 28
  • 38
1

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);
?>

Live example

Jean B.
  • 176
  • 6