如何按日期对Json进行排序?

时间:2014-04-18 01:31:36

标签: php json date usort

我是php和Jsons的新手,我正在尝试按日期安排Json的内容。我知道usort()函数,但到目前为止我一直没有成功使用它。这是Json:

[{"id":"1","poi_id":"36","date":"1993-05-14","url":"#","p_flag":"0"},{"id":"2","poi_id":"36","date":"2000-05-14","url":"#","p_flag":"0"},{"id":"3","poi_id":"36","date":"1992-05-14","url":"#","p_flag":"0"}]

我一直想做的是:

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

    return $dA->format('y') - $dB->format('y');
}
$data=json_decode($unsorted, true);
print_r(usort($data, 'sortByYear'));

1 个答案:

答案 0 :(得分:3)

<?php
    $unsorted = '[{"id":"1","poi_id":"36","date":"1993-05-14","url":"#","p_flag":"0"},{"id":"2","poi_id":"36","date":"2000-05-14","url":"#","p_flag":"0"},{"id":"3","poi_id":"36","date":"1992-05-14","url":"#","p_flag":"0"}]';

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

    return $dA > $dB;
}
$data=json_decode($unsorted, true);
usort($data, 'sortByYear');
print_r($data);

Demo

几点:

  1. 您需要按全年Y排序,而不是最后两位数y。当你跨越新千年时,你会遇到问题。

  2. 我使用>进行比较。这种方式更清楚。

  3. usort()排序到位,因此不返回任何数组。这意味着您需要在原始数组上调用var_dump(),而不是usort()