1

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

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

谢谢

4

2 回答 2

0
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;
    }
}
于 2009-10-28T11:44:05.433 回答
0
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);
}
于 2009-10-28T11:39:29.793 回答