How do I sort a flat Json by Date?

十年热恋 提交于 2020-01-25 03:41:09

问题


I am pretty new to php and Jsons and I am trying to arrange contents of a Json by date. I know about the usort() function but so far I have been unsuccessful at using it. This is the 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"}]

What I have been trying to do is this:

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:


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

A few points:

  1. You need to sort by the full year Y, not the last twp digits y. When you cross over the new millennium you have problems.

  2. I used > for the comparison. It is clearer what the sort is that way.

  3. usort() sorts in place so no array is returned. This means you need to call var_dump() on the original array, not usort().



来源:https://stackoverflow.com/questions/23146068/how-do-i-sort-a-flat-json-by-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!