PHP按月和年排序数组

时间:2009-10-28 11:32:57

标签: php 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

由于

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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;
    }
}