user3264863
user3264863

Reputation: 278

How to sort array using object element in php?

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

Answers (2)

Jean B.
Jean B.

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

Live example

Upvotes: 1

ddb
ddb

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

Related Questions