PHP按月份然后按年份对数组排序

PHP按月份然后按年份对数组排序,php,usort,Php,Usort,我有一个数组或带有日期的对象,我希望按其排序 我有以下传递给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

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

我有以下传递给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

谢谢

功能排序月($a,$b){
如果($a->received_date==$b->received_date)
返回0;
列表($ay、$am、$ad)=分解('-',$a->接收日期);
列表($by,$bm,$bd)=分解('-',$b->接收日期);
如果($am=$bm)
返回($a->接收日期<$b->接收日期?-1:1);
其他的
回报($am<$bm?-1:1);
}

顺便说一下:
intval(日期('m',$a->received_date))可以缩写为
idate('m',$a->received\u date)
如问题所示,OP的日期是
YYYY-MM-DD
格式,而不是UNIX时间戳。因此,您需要执行
$a=strotime($a->received_date)
$b=strotime($b->received_date)
才能在
$a
$b
上使用
date()
idate()
函数。非常感谢。真棒:)
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;
    }
}