如何按日期排序平面Json? [英] How do I sort a flat Json by Date?

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

问题描述

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

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

这样做是这样的:

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

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


解决方案

  ?php 
$ unsorted ='[{id:1,poi_id:36,date:1993-05-14,url:#,p_flag 0},{id:2,poi_id:36,日期:2000-05-14,url:#,p_flag ,{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);

演示



几点:


  1. 您需要在全年排序 Y ,而不是最后的twp数字 y 。当您跨越新千年时,您有问题。


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


  3. usort()排序到位,所以没有数组被退回这意味着您需要调用原始数组上的 var_dump(),而不是 usort()

    / li>


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

解决方案

<?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().

这篇关于如何按日期排序平面Json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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