问题
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 )
回答1:
use a custom sort function, something like this.
var months = new Array(12);
months['Jan'] = 1;
months['Feb'] = 2;
months['Mar'] = 3;
months['Apr'] = 4;
months['May'] = 5;
months['Jun'] = 6;
months['Jul'] = 7;
months['Aug'] = 8;
months['Sep'] = 9;
months['Oct'] = 10;
months['Nov'] = 11;
months['Dec'] = 12;
function sortDate(a,b)
{
var m1 = a.substring(0,3);
var y1 = a.substring(4);
var m2 = b.substring(0,3);
var y2 = b.substring(4);
if(Number(y1)>Number(y2)) {
return 1;
} else if(Number(y1)<Number(y2)) {
return -1;
} else {
if(months[m1]>months[m2]) {
return 1;
} else if(months[m1]<months[m2]) {
return -1;
}
}
return 0;
}
var myArray = ['Oct/08', 'Jan/09', 'Mar/09', 'May/07', 'Apr/08', 'Dec/06'];
alert(myArray.sort(sortDate));
回答2:
You can Check This Link :-
Use the ISO (yyyy-mm-dd) format rather than the "english" format, and then just use the ksort function to get them in the right order.
There's no need to remove the hyphens, ksort will do an alphanumeric comparison on the string keys, and the yyyy-mm-dd format works perfectly well as the lexical order is the same as the actual date order.
来源:https://stackoverflow.com/questions/8351929/how-one-can-sort-an-array-of-values-by-year-and-month-in-php