Search code examples
phparrayssortingdatetime

Sort array of objects by datetime values formatted as Y-n-d H:i:s


How can I re-arrange an 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?


Solution

  • 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');