Does anybody have an idea how can I sort this array by key (date) in PHP?
Array
(
[2011-02-16] => Array
(
[date] => 2011-02-16
http://www.php.net/manual/en/function.array-multisort.php
Would example #3 suit your needs?
A better answer would be to use uksort which is used to sort keys with a user-defined function (considering that these dates cannot always be compared and cannot be sorted with ksort
without first applying strtotime
to the keys):
function sort_by_date_keys($date_key1, $date_key2) {
// reverse the order of the $date_keys for "oldest to newest"
return strtotime($date_key2) - strtotime($date_key1);
);
uksort($array, 'sort_by_date_keys');
This method is more defined than uasort
as it was tailored for keys.
Example:
$array = array(
'1/1/12' => 'foo1',
'1/1/13' => 'foo2'
);
uksort($array, 'sort_by_date_keys');
// output
$array = array(
'1/1/13' => 'foo2',
'1/1/12' => 'foo1'
);
Since your array already has the date in the keys, why not just use ksort
? The string comparison should work fine since you're using YYYY-MM-dd format.