0

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 ?

1
  • 1
    You're converting your JSON to an array, so you need to access it as such. return $a["4"] > $b["4"] ? -1 : 1; }); Commented Oct 24, 2017 at 14:06

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

is working but how get my $result ? my json is dont work :S why
The json you showed is invalid. It needs to be a root, either as an object or an array of objects. In case, your json should be an object with several where the dates are the keys. Try put your json on jsonlint.com
jsonlint.com - Valid JSON my json data , i,did my result like u thanks man.
0

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?

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.