3

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"}]
}
}
JamieB
  • 923
  • 9
  • 30
  • Specially when *just searching* the Stack brings an answer to 90%-95% of our code needs. – brasofilo Oct 20 '13 at 22:10
  • Thanks for the input so far. I am aware I need to use usort but I am unsure as to how to achieve it with items nested this deep in the array. – JamieB Oct 20 '13 at 22:12

1 Answers1

7

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.

futureal
  • 3,025
  • 1
  • 22
  • 33