dsjq6977 2017-01-09 08:17
浏览 226
已采纳

我如何在PHP中按日期排序数组

I have this array and i want to sort it in ascending order by date. I tried various answers from this site but none of them is working right. So how can I do this?

Array
(
    [0] => 09/01/2017
    [1] => 08/01/2017
    [2] => 07/01/2017
    [3] => 06/01/2017
    [4] => 05/01/2017
    [5] => 04/01/2017
    [6] => 03/01/2017
    [7] => 02/01/2017
    [8] => 01/01/2017
    [9] => 12/12/2016
    [10] => 11/12/2016
    [11] => 10/12/2016
    [12] => 09/12/2016
    [13] => 25/12/2016
    [14] => 24/12/2016
    [15] => 23/12/2016
    [16] => 26/12/2016
    [17] => 28/12/2016
    [18] => 30/12/2016
    [19] => 29/12/2016
    [20] => 22/12/2016
    [21] => 27/12/2016
    [22] => 15/12/2016
    [23] => 16/12/2016
    [24] => 14/12/2016
    [25] => 13/12/2016
    [26] => 17/12/2016
    [27] => 18/12/2016
    [28] => 20/12/2016
    [29] => 19/12/2016
    [30] => 21/12/2016
)

I am using PHP. This is what i tried so far. This function doesn't sort as mentioned in all other questions.

$data = array listed above;
function cmp($a, $b)
{
    if (strtotime($a) == strtotime($b))
    {
        return 0;
    }
    return (strtotime($a) < strtotime($b)) ? -1 : 1;
}

uasort($data, "cmp");
  • 写回答

4条回答 默认 最新

  • douniang3866 2017-01-09 08:30
    关注

    For you string is dd/mm/yy type, cannot directly used by strtotime or date_create. You can use DataTime to create the datetime, then use the datetime compare operators.

    usort($array, function($a, $b){return DateTime::createFromFormat('d/m/Y', $a) > DateTime::createFromFormat('d/m/Y', $b);});
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看