php - Sort array with date as key
A slightly more complex solution, which nonetheless works for almost any date format, is based on the uksort function.
First we define a callback function that compares two dates (comparator):
function compare_date_keys($dt1, $dt2) {
return strtotime($dt1) - strtotime($dt2);
}
Now we can use the just defined function as the second parameter in uksort, as in the example below:
uksort($arr, "compare_date_keys");
As a result the function will treat the key as a date and sort the array in ascending order (less recent first).
Note that we can easily tweak the comparator to support different use cases. For example, sorting by date descending (most recent first) can be accomplished by simply replacing the function's return expression with the following:
return strtotime($dt2) - strtotime($dt1);
With the dates in that format, an alphabetical comparison will work just fine. Use the PHP function ksort.
ksort($arr);