且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何可以进行排序按年份和月份在PHP中值的数组?

更新时间:2023-01-30 15:11:52

使用自定义排序功能,这样的事情。

  VAR个月=新阵列(12);
几个月['扬'] = 1;
几个月['二月'] = 2;
几个月['月'] = 3;
几个月['月'] = 4;
几个月['五一'] = 5;
几个月['君'] = 6;
几个月['七月'] = 7;
几个月['八月'] = 8;
几个月['九月'] = 9;
几个月['十月'] = 10;
几个月['月'] = 11;
几个月['月'] = 12;功能sortDate(A,B)
  {
VAR M1 = a.substring(0,3);
变种Y1 = a.substring(4);
VAR M2 = b.substring(0,3);
变种Y2 = b.substring(4);如果(号码(Y1)>编号(Y2)){
    返回1;
}否则如果(编号(Y1)&所述;编号(Y2)){
    返回-1;
}其他{
    如果(月[M1]≥月[2]){
        返回1;
    }否则如果(月[M1<个月[2]){
        返回-1;
    }
}返回0;
   }myarray的无功= ['十月/ 08','月/ 09','月/ 09','月/ 07','月/ 08','月/ 06'];
警报(myArray.sort(sortDate));

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.

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));