[英]PHP Sort array by month then year
I have an array or objects with a dates which I wish to sort by. 我有一个数组或带有日期的对象,希望将其排序。
I have the following custom function that I pass to usort 我将以下自定义函数传递给usort
function sortMonths($a, $b) {
if ( $a->received_date == $b->received_date ) return 0;
return ($a->received_date > $b->received_date) ? 1 : -1;
}
Which does as required and sorts dates so I get: 哪个按要求进行并排序日期,所以我得到:
2009-05-01 2009-03-01 2008-05-01 2008-03-01 2007-03-01 2009-05-01 2009-03-01 2008-05-01 2008-03-01 2007-03-01
However how do I group together by months then order by the year to obtain: 但是,我如何按月分组,然后按年订购以获得:
2009-05-01 2008-05-01 2009-03-01 2008-03-01 2007-03-01 2009-05-01 2008-05-01 2009-03-01 2008-03-01 2007-03-01
Thanks 谢谢
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.