Possible Duplicate:
How to sort a date array in PHP
I want to sort out the array of values by year and month, I’ve attached my code here,
Year is sorting in descending in my script, i want to sort out year by ascending order,
<?php
$array = array("2011-September_38","2011-June_4","2010-November_9","2011-November_29","2010-December_19");
function monthCompare($a, $b) {
$count = substr($a,strpos($a,'_'));
$count =strlen($count);
$count1 = substr($b,strpos($b,'_'));
$count1 =strlen($count1);
$a = strtolower(substr($a,5,-$count));
$b = strtolower(substr($b,5,-$count1));
$months = array(
'january'=> 1,
'february'=> 2,
'march'=>3,
'april'=>4,
'may'=>5,
'june'=>6,
'july'=>7,
'august'=>8,
'september'=>9,
'october'=>10,
'november'=>11,
'december'=>12
);
if($a == $b)
return 0;
if(!isset($months[$a]) || !isset($months[$b]))
return $a > $b;
return ($months[$a] > $months[$b]) ? 1 : -1;
}
usort($array, "monthCompare");
print_r($array);
?>
Actual output:
Array
(
[0] => 2011-June_4
[1] => 2010-Marh_19
[2] => 2011-September_38
[3] => 2010-November_9
[4] => 2011-November_29
)
Required output:
Array ( [0] => 2010-Marh_19
[1] => 2010-November_9
[2] => 2011-June_4
[3] => 2011-September_38
[4] => 2011-November_29 )
use a custom sort function, something like this.