我想按年份和月份来计算值数组,我已将代码附加到此处, 年份在我的脚本中按降序排序,我想按升序排序年份
<?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);
?>
实际输出:
Array
(
[0] => 2011-June_4
[1] => 2010-Marh_19
[2] => 2011-September_38
[3] => 2010-November_9
[4] => 2011-November_29
)
必填项:
Array ( [0] => 2010-Marh_19
[1] => 2010-November_9
[2] => 2011-June_4
[3] => 2011-September_38
[4] => 2011-November_29 )
答案 0 :(得分:1)
使用自定义排序功能,就像这样。
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));
答案 1 :(得分:0)
使用ISO(yyyy-mm-dd)格式而不是“英语”格式,然后使用ksort函数以正确的顺序获取它们。
没有必要删除连字符,ksort会对字符串键进行字母数字比较,而yyyy-mm-dd格式的效果非常好,因为词法顺序与实际日期顺序相同。