2009-10-28 50 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