Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a JSON array with PHP

First of all i'm a complete newbie to this, i have searched for solutions but none seem to do the trick.

So I am trying to sort this JSON array by date but i don't really know i should tackle this, any tips in the right direction are much appreciated!

["info":[
{"id":1, "title":"original title", "name":"john doe", "date":"2010-05-15"}, 
{"id":2, "title":"another title", "name":"foo bar", "date":"2009-04-11"},
...

So i'm getting the data like this

$data=file_get_contents('jsondata...');
$d=json_decode($data,true);

I would like to sort the data by date, any ideas how i should approach this? Is it also possible to return the year value only? So the output would be 2009 instead of 2009-04-11?

Thanks in advance

like image 295
xtoffer Avatar asked Mar 21 '12 16:03

xtoffer


People also ask

How do you sort an array of objects in PHP?

The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.


1 Answers

You can use usort and a custom comparison function:

$data = '{"info":[{"id":1, "title":"original title", "name":"john doe", "date":"2010-05-15"}, {"id":2, "title":"another title", "name":"foo bar", "date":"2009-04-11"}]}';

$info = json_decode($data, true)['info'];

usort($info, function ($a, $b) {
    return $a['date'] <=> $b['date'];
});

<=> works on strings here because a string comparison is also a date comparison when your dates are formatted as YYYY-MM-DD.

Then, to show the year value for an entry, you can parse the date into a DateTime and reformat it:

$date = DateTime::createFromFormat('Y-m-d', $item['date']);
$year = $date->format('Y');

Here's a demo.

like image 130
Ry- Avatar answered Sep 19 '22 23:09

Ry-