Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects by date field

Tags:

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 ?

like image 288
Nadine Avatar asked Aug 19 '11 21:08

Nadine


People also ask

How do you sort an array of objects by date?

To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.

How do I sort a date and time in TypeScript?

To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.


1 Answers

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'); 
like image 134
Arnaud Le Blanc Avatar answered Nov 30 '22 18:11

Arnaud Le Blanc