按日期对PHP中的json数组进行排序? [英] Sort json array in PHP by date?

查看:228
本文介绍了按日期对PHP中的json数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对已从xml(rss)转换为json的新闻项目列表进行排序.合并提要后,我想按日期顺序对它们进行排序,但是我不确定实现此目标的最佳方法.

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.

json响应如下:

{ "success":true,
"message":"",
"data":{
"title":"Feed Name",
"item":[{
"title":"test",
"pubdate":"Sun, 20 Oct 2013 21:36:42 GMT"}]
}
}

推荐答案

要在PHP中进行操作,您首先需要将其解码为PHP数组:

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'
       )
     )
   )
 )

因此,您可以使用它来确定排序功能的工作方式.不过,尚不清楚的是,是要仅对item数组的元素进行排序,还是要进行更复杂的排序(因为您提到了合并提要时").

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").

仅对item数组进行排序是一项相当简单的任务,每个元素只是一个具有两个自己元素的数组,一个元素名为title,另一个元素名为pubdate.在这种情况下,您的排序函数如下所示:

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.

这篇关于按日期对PHP中的json数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆