【问题标题】:PHP Sort array by month then yearPHP 按月和年对数组进行排序
【发布时间】:2009-10-28 11:32:56
【问题描述】:

我有一个数组或对象,其中包含我希望排序的日期。

我有以下自定义函数传递给 usort

    function sortMonths($a, $b) {
    if ( $a->received_date == $b->received_date ) return 0;
    return ($a->received_date > $b->received_date) ? 1 : -1;
}

根据需要对日期进行排序,以便我得到:

2009-05-01 2009-03-01 2008-05-01 2008-03-01 2007-03-01

但是我如何按月份分组然后按年份排序以获得:

2009-05-01 2008-05-01 2009-03-01 2008-03-01 2007-03-01

谢谢

【问题讨论】:

    标签: php usort


    【解决方案1】:
    function sortMonths($a, $b) {
        if ($a->received_date == $b->received_date)
            return 0;
    
        list($ay,$am,$ad) = explode('-', $a->received_date);
        list($by,$bm,$bd) = explode('-', $b->received_date);
    
        if ($am == $bm)
            return ($a->received_date < $b->received_date ? -1 : 1);
        else
            return ($am < $bm ? -1 : 1);
    }
    

    【讨论】:

    • 非常感谢。太棒了:)
    【解决方案2】:
    function sortMonths($a, $b) {
        $a = strtotime($a->received_date);
        $b = strtotime($b->received_date);
        if ( $a == $b ) return 0;
    
        $ayear  = intval(date('m',$a)); // or idate('m', $a)
        $amonth = intval(date('Y',$a)); // or idate('Y', $a)
    
        $byear  = intval(date('m',$b));  // or idate('m', $b)
        $bmonth = intval(date('Y',$b));  // or idate('Y', $b)
    
        if ($amonth == $bmonth) { 
            return ($ayear > $byear) ? 1 : -1;
        } else {
            return ($amonth > $bmonth) ? 1 : -1;
        }
    }
    

    【讨论】:

    • 顺便说一句:intval(date('m',$a-&gt;received_date));可以简写成idate('m',$a-&gt;received_date);
    • 正如问题所暗示的,OP 的日期为 YYYY-MM-DD 格式,而不是 UNIX 时间戳。因此,您需要执行$a = strtotime($a-&gt;received_date)$b = strtotime($b-&gt;received_date) 才能在$a$b 上使用date()idate() 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2019-01-25
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多