繁体   English   中英

PHP按月然后按年对数组进行排序

[英]PHP Sort array by month then year

我有一个数组或带有日期的对象,希望将其排序。

我将以下自定义函数传递给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

谢谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM