Sort array of objects by date field

2020-03-01 05:16发布

问题:

How can I re-arrange a array of objects like this:

 [495] => stdClass Object
        (
         [date] => 2009-10-31 18:24:09
         ...
        )
 [582] => stdClass Object
        (
         [date] => 2010-2-11 12:01:42
         ...
        )
 ...

by the date key, oldest first ?

回答1:

usort($array, function($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
});

Or if you don't have PHP 5.3:

function cb($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
}
usort($array, 'cb');


回答2:

Since the original question is about sorting arrays of stdClass() objects, here's the code which would work if $a and $b are objects:

usort($array, function($a, $b) {
    return strtotime($a->date) - strtotime($b->date);
});

Or if you don't have PHP 5.3:

function cb($a, $b) {
    return strtotime($a->date) - strtotime($b->date);
}
usort($array, 'cb');


回答3:

I wanted to expand on arnaud576875's answer. I ran across this same issue, but with using DateTime objects. This is how I was able to accomplish the same thing.

usort($array, function($a, $b) {
    return $a['date']->format('U') - $b['date']->format('U');
});


回答4:

I wanted to expand on arnaud576875 and Michael Irigoyen.

Same issue with object containing dateTime with Symphony.

I coudn't use $a['date'] because it was not an key array.

usort($verifications, function($a, $b) {
   return $a->getDate()->format('U') - $b->getDate()->format('U');
});

This solved my problem