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.

6

2 Answers 2

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

?>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.