2

只是想知道是否有人可以优化这个 usortMonths() 函数变得更好?基本上我有一个未排序的月份数组,$bob,我希望它们按月份排序,而不是按字母顺序。

该代码运行良好,但这是我第一次使用 uSort,我不介意是否有人可以提出任何改进建议?

function usortMonths($a, $b) {
$months = array('JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER');
    $key = array(0 => 0,1 => 0,2 => FALSE, 3 => FALSE);
    if(array_search(strtoupper($a),$months)!==FALSE) {
        $key[0] = array_search(strtoupper($a),$months);
        $key[2] = TRUE; }
    if(array_search(strtoupper($b),$months)!==FALSE) {
        $key[1] = array_search(strtoupper($b),$months);
        $key[3] = TRUE; }
    if($key[2] && $key[3]){
        if($key[0] < $key[1]) {return -1;}
        if($key[0] == $key[1]){return 0;}
        if($key[0] > $key[1]) {return 1;}
    }
}

$bob = array('april','august','december','february','January','july','june','march','may','november','october','september',);       
usort($bob,"usortMonths");
var_dump($bob);
4

1 回答 1

2

这个怎么样?

function usortMonths($a, $b) {
    $months = array('JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER');
    return array_search(strtoupper($a), $months) - array_search(strtoupper($b), $months);
}
于 2012-06-19T11:47:58.007 回答