zeaolanos
zeaolanos

Reputation: 211

sort Json data in php ? Different specific data?

This is json data in webservice, I need to sort this kind of information by top to date sort 2017..bla - 2015..bla -2014, maybe sort value "4" or title 2015 blabla.... value in a PHP script, how can I do?

"2015-09-11 09:18:11.023151": {
    "1": "4422",
    "2": "asd",
    "3": "aaa",
    "4": "2015-09-11 09:18:11.023151"
    },
"2014-10-29 13:33:14.325827": {
    "1": "5852",
    "2": "shfe",
    "3": "sds",
    "4": "2014-10-29 13:33:14.325827"
},
"2017-11-10 09:18:11.315102": {
    "1": "2323",
    "2": "sfd",
    "3": "sdf",
    "4": "2017-11-10 09:18:11.315102"
}

i try :

$example= json_decode($result, true);


usort($example, function($a, $b) {  
    return $a->{"4"} > $b->{"4"} ? -1 : 1; }); 

echo json_encode($example);

how we can do it ?

Upvotes: 0

Views: 57

Answers (2)

Anderson Andrade
Anderson Andrade

Reputation: 579

Please, try this.

$result = '{"2015-09-11 09:18:11.023151":{"1":"4422","2":"asd","3":"aaa","4":"2015-09-11 09:18:11.023151"},"2014-10-29 13:33:14.325827":{"1":"5852","2":"shfe","3":"sds","4":"2014-10-29 13:33:14.325827"},"2017-11-10 09:18:11.315102":{"1":"2323","2":"sfd","3":"sdf","4":"2017-11-10 09:18:11.315102"}}';

$example= json_decode($result, true);
usort($example, function($a, $b) { return $a["4"] > $b["4"] ? -1 : 1; }); 
echo json_encode($example);

Upvotes: 1

frank Walleway
frank Walleway

Reputation: 136

I think I fixed your problem. I started out by converting the json to an array like you did with $array = json_decode($json, true);

next instead of using usort() i used asort().

Asort sorts your array from high to low and works on dates (in my case)

http://php.net/manual/en/function.asort.php

Is this what you mean?

Upvotes: 0

Related Questions