如何使用PHP对JSON数组进行排序

时间:2021-12-01 14:58:04

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!

所以我试图按日期排序这个JSON数组,但我真的不知道我应该解决这个问题,任何正确方向的提示都非常感谢!

["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?

我想按日期排序数据,任何想法我应该如何处理这个?是否也可以仅返回年份值?那么产量将是2009年而不是2009-04-11?

Thanks in advance

提前致谢

4 个解决方案

#1


9  

You can use usort and a custom comparison function:

您可以使用usort和自定义比较功能:

$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.

<=>在这里处理字符串,因为当您的日期格式为YYYY-MM-DD时,字符串比较也是日期比较。

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

然后,要显示条目的年份值,您可以将日期解析为DateTime并重新格式化:

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

Here's a demo.

这是一个演示。

#2


0  

You have to convert the date to a sortable format first. I think that strtotime() does the job. After that you can output whatever with strftime().

您必须先将日期转换为可排序格式。我认为strtotime()完成了这项工作。之后,您可以使用strftime()输出任何内容。

#3


0  

Use uasort to sort the array with user-defined function and strtotime to parse the date to timestamp.

使用uasort使用用户定义的函数和strtotime对数组进行排序,以将日期解析为时间戳。

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

$arr = json_decode($json)->info;
uasort($arr, function($item1, $item2){
    return strtotime($item1->date) > strtotime($item2->date);
});

Will output

Array
(
    [1] => stdClass Object
        (
            [id] => 2
            [title] => another title
            [name] => foo bar
            [date] => 2009-04-11
        )

    [0] => stdClass Object
        (
            [id] => 1
            [title] => original title
            [name] => john doe
            [date] => 2010-05-15
        )

)

#4


0  

Something like the following should get you started:

以下内容应该让您入门:

<?php

function sortDate($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}

$input = array('info' => array(array('id' => 2, 'date' => '2019-04-11'), array('id' => 1, 'date' => '2010-05-15')));

usort($input['info'], 'sortDate');
print_r($input);

#1


9  

You can use usort and a custom comparison function:

您可以使用usort和自定义比较功能:

$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.

<=>在这里处理字符串,因为当您的日期格式为YYYY-MM-DD时,字符串比较也是日期比较。

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

然后,要显示条目的年份值,您可以将日期解析为DateTime并重新格式化:

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

Here's a demo.

这是一个演示。

#2


0  

You have to convert the date to a sortable format first. I think that strtotime() does the job. After that you can output whatever with strftime().

您必须先将日期转换为可排序格式。我认为strtotime()完成了这项工作。之后,您可以使用strftime()输出任何内容。

#3


0  

Use uasort to sort the array with user-defined function and strtotime to parse the date to timestamp.

使用uasort使用用户定义的函数和strtotime对数组进行排序,以将日期解析为时间戳。

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

$arr = json_decode($json)->info;
uasort($arr, function($item1, $item2){
    return strtotime($item1->date) > strtotime($item2->date);
});

Will output

Array
(
    [1] => stdClass Object
        (
            [id] => 2
            [title] => another title
            [name] => foo bar
            [date] => 2009-04-11
        )

    [0] => stdClass Object
        (
            [id] => 1
            [title] => original title
            [name] => john doe
            [date] => 2010-05-15
        )

)

#4


0  

Something like the following should get you started:

以下内容应该让您入门:

<?php

function sortDate($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}

$input = array('info' => array(array('id' => 2, 'date' => '2019-04-11'), array('id' => 1, 'date' => '2010-05-15')));

usort($input['info'], 'sortDate');
print_r($input);