如何排序JSON数组用PHP [英] How to sort a JSON array with PHP

查看:249
本文介绍了如何排序JSON数组用PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我是一个完整的新手到这个第一,我已经寻找解决方案,但没有人可以做的伎俩。

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

所以,我想按日期排序此JSON数组,但我真的不知道我应该解决这个问题,在正确的方向任何提示得多AP preciated!

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

我想按日期对数据进行排序,任何想法如何,我应该处理这个?是否也可以只返回年份值?所以输出将是2009年而不是2009-04-11?

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?

在此先感谢

推荐答案

您可以使用 usort 和一个自定义比较函数:

You can use usort and a custom comparison function:

function sortByYear($a, $b) {
    $dA = new DateTime($a['date']);
    $dB = new DateTime($b['date']);

    return $dA->format('y') - $dB->format('y');
}

$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"}]}';

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

usort($info, 'sortByYear');

这里有一个演示。

请注意,我必须解决您的JSON一点点; json_parse 将无法解析,除了一个JSON的对象的东西。这是previously阵列。你可以选择你想处理这个问题的任何方式。

Note that I had to fix up your JSON a little bit; json_parse won't parse anything except for a JSON object. It was previously an array. You can choose whatever way you'd like of dealing with this.

这篇关于如何排序JSON数组用PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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