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
Sure thing. I answered this exact post yesterday, too.
Sorting 2 arrays to get the highest in one and lowest in another
In your case, it will be something like...
$myArray= subval_sort($myArray,'date');
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val){
$c[] = $a[$key];
}
return $c;
}
EDIT
The answer by shamittomar
is better though :)
Use the uasort function, which is user customizable sorting. Like this:
function cmp($a, $b)
{
if ($a['date'] == $b['date'])
{
return 0;
}
return ($a['date'] < $b['date']) ? -1 : 1;
}
uasort($your_array, "cmp");
Well, as sorting on the key would do it, ksort() would work for you!
But if you really want to sort on the date element, you would use uasort() with a sort function like this
function compare($a, $b)
{
if ($a['date']==$b['date']) return 0;
return ($a['date']>$b['date'])?1:-1;
}
uasort($myarray, 'compare');
have you tried ksort? http://www.php.net/manual/en/function.ksort.php
This should help you brush up on the basics of array sorting in PHP
http://www.the-art-of-web.com/php/sortarray/
Something like this would sort your problem however:
usort($array, "cmp");
function cmp($a, $b){
return strcmp($b['date'], $a['date']);
What you want is UASORT.
http://us3.php.net/manual/en/function.uasort.php
function would be like:
function cmp($a, $b) {
$d1 = strtotime($a['date']);
$d2 = strtotime($b['date']);
if ($d1 == $d2) {
return 0;
}
return ($d1 < $d2) ? -1 : 1;
}