Robert Ross Robert Ross - 12 days ago 6
JSON Question

Sorting an array with json records by a date property in php?

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":"asd@bv.com","date":"2016-11-03","time":"1pm","reason":"some reason","isApproved":1,"label":"success","status":"Approved"},{"fullName":"Robert Royce","userName":"user1","phone":"+4460475640","email":"asd@asf.cv","date":"2016-11-17","time":"130pm","reason":"some reason","isApproved":1,"label":"success","status":"Approved"},{"fullName":"Pesho Zdr","userName":"user4","phone":"+4560477640","email":"grozdan@abv.bg","date":"2016-11-17","time":"130pm","reason":"some reason","isApproved":0,"label":"success","status":"Approved"}]

Answer
$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);
Comments