Anyone know the best way to sort an array by date? I would set the date as the array key but I don't want to overwrite anything with the same date. Thx in advance!
Asked
Active
Viewed 91 times
0
-
1Possible duplicate of [Multidim sorts?](http://stackoverflow.com/questions/6590117/multidim-sorts) Otherwise, please provide more information. Why *two* arrays? – deceze Jul 08 '11 at 05:59
-
@deceze, they're two arrays of diff objects which I need to combine into one array and sort by time. It appears as though usort() is my tool for the job. – blacktie24 Jul 08 '11 at 06:01
-
Possible duplicate of [How to sort a date array](http://stackoverflow.com/questions/597863/how-to-sort-a-date-array-in-php) – Stephane Gosselin Jul 08 '11 at 06:06
-
Possible duplicate of [How to sort a date array](http://stackoverflow.com/questions/597863/how-to-sort-a-date-array-in-php). – Stephane Gosselin Jul 08 '11 at 06:07
2 Answers
2
Something along these lines:
$merged = array_merge($array1, $array2);
usort($merged, function ($a, $b) { return $a->time - $b->time; });
The $a->time
syntax depends on what exactly that object looks like, but you get the idea.

deceze
- 510,633
- 85
- 743
- 889
1
It is hard to see without the date format posted or a code example. You could use the ksort function to get them in the right order. You just have to use the ISO (yyyy-mm-dd) format rather than the "english" format, and then get them in the right order with ksort.
If you are dealing with a multi-dimensional array, you could use uksort to sort by keys with a callback. In the callback, simply parse the date to a timestamp, wich can easily be sorted.

Stephane Gosselin
- 9,030
- 5
- 42
- 65