tags:

views:

337

answers:

2

Hi,

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

    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

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

Thanks

A: 
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);
}
reko_t
Thank you very much. Awesome :)
rookang
A: 
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;
    }
}
kipelovets
By the way: `intval(date('m',$a->received_date));` can be shortend to `idate('m',$a->received_date);`
Stefan Gehrig
thanks, but even though reko_t's solution is better)
kipelovets
As the question suggests, the OP has dates in the `YYYY-MM-DD` format and not as UNIX timestamps. Therefore you need to do `$a = strtotime($a->received_date)` and `$b = strtotime($b->received_date)` to be able to use the `date()` or `idate()` function on `$a` and `$b`.
Stefan Gehrig