2009-10-28 49 views
1

我有一個數組或具有日期的對象,我希望按其排序。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

感謝

回答

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

非常感謝你。真棒:) – rookang 2009-10-28 12:05:18

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; 
    } 
} 
+0

順便說一句:'intval(date('m',$ a-> received_date));'可以縮短爲'idate('m',$ a-> received_date);' – 2009-10-28 11:47:03

+0

謝謝,儘管reko_t的解決方案更好) – kipelovets 2009-10-28 11:48:46

+0

如問題所示,OP的日期是'YYYY-MM-DD'格式,而不是UNIX時間戳。因此,您需要執行'$ a = strtotime($ a-> received_date)'和'$ b = strtotime($ b-> received_date)''以使用'date()'或'idate()'函數在'$ a'和'$ b'上。 – 2009-10-28 11:49:48