0

I have a json file with a field date in it, which is not in a specific format and it should stay like this. I am wondering how can is sort this json with php, so the records with the most recent date appear in the beginning in the json and so on until the end in descending order.

I tried a lot of things, but nothing worked for me.

Here is how the json looks :

    [
      {"fullName":"John Doe","userName":"user2",
       "phone":"+1234124512","email":"[email protected]",
       "date":"2016-11-03","time":"1pm","reason":"some reason",
       "isApproved":1,"label":"success","status":"Approved"}, 
      {"fullName":"Robert Royce","userName":"user1",
       "phone":"+4460475640","email":"[email protected]","date":"2016-11- 17",
        "time":"130pm","reason":"some reason",
       "isApproved":1,"label":"success","status":"Approved"},
      {"fullName":"Pesho Zdr","userName":"user4",
       "phone":"+4560477640","email":"[email protected]","date":"2016-11-17",
       "time":"130pm","reason":"some reason",
       "isApproved":0,"label":"success","status":"Approved"}
    ]

1 Answer 1

2
$json = // your json here
$jsonArray = json_decode($json, true);
usort($jsonArray, function ($a, $b) {
    return $a['date'] > $b['date'] ? -1 : 1;
});
$json = json_encode($jsonArray);

First step

First of all transform json into array with json_decode

$jsonArray = json_decode($json, true);

Second parameter is used to indicate that output needs to be an array and not an object

Second step

Order the array; it seems that usort can help you

usort($jsonArray, function ($a, $b) {
    return $a['date'] > $b['date'] ? -1 : 1;
});

This will walk the array from first value to last comparing the first ($a) to the second ($b).
In particular we are interested in date value.
To make usort work as expected, you need to return a value from the closure to tell comparison result. Possible results are

  • 0 to indicate that they have same value
  • < 0 to indicate that first element is smaller than second
  • > 0 to indicate that first element is greater than second

Third step

Finally, convert all back to json format with json_encode

$json = json_encode($jsonArray);
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks for your answer. Could you explain this part : $b['date'] ? -1 : 1;
@RobertRoss I was updating my answer ;) here you are!
Thanks. Works perfect!

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.