Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort json array in PHP by date? [closed]

I am trying to sort a list of news items that have been converted from xml (rss) to json. I'd like to have them sorted by date order after the feeds have been combined but I am not sure on the best way to achieve it.

The json response looks like:

{ "success":true,
"message":"",
"data":{
"title":"Feed Name",
"item":[{
"title":"test",
"pubdate":"Sun, 20 Oct 2013 21:36:42 GMT"}]
}
}
like image 297
JamieB Avatar asked Dec 14 '25 03:12

JamieB


1 Answers

To do it in PHP, you'd first decode it to a PHP array:

 $data = json_decode($yourJsonVariable, true);

Now with your data as above, that is going to give you an array that looks something like:

 array(
   'success' => true,
   'data' => array(
     'title' => 'Feed Name',
     'item' => array(
       0 => array(
         'title' => 'test',
         'pubdate' => 'Sun, 20 Oct 2013 21:36:42 GMT'
       )
     )
   )
 )

So using that, you can figure out how you'd like your sorting function to work. What is unclear, though, is if you are trying to sort just the elements of the item array, or if you are trying to do some more complex sort (since you mentioned "when the feeds are combined").

To sort only the item array is a fairly simple task, sine each element is just an array with two elements of its own, one named title and another named pubdate. In that case your sort function looks something like:

 usort($data['data']['item'], function($a, $b) {
   return (strtotime($a['pubdate']) < strtotime($b['pubdate']) -1 : 1);
 });

If you need to sort the entire array or a different part of it, you should be able to adapt that function to do so.

like image 88
futureal Avatar answered Dec 15 '25 17:12

futureal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!