Sort array of objects by date field

后端 未结 4 1959
天涯浪人
天涯浪人 2021-01-01 15:57

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

 [495] => stdClass Object
        (
         [date] => 2009-10-31 18:24:09
         ...
        )
 [         


        
相关标签:
4条回答
  • 2021-01-01 16:25

    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

    0 讨论(0)
  • 2021-01-01 16:26

    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');
    });
    
    0 讨论(0)
  • 2021-01-01 16:32
    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');
    
    0 讨论(0)
  • 2021-01-01 16:33

    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');
    
    0 讨论(0)
提交回复
热议问题