PHP uSort优化?

时间:2012-06-19 11:28:26

标签: php usort

只是想知道是否有人可以优化这个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);

1 个答案:

答案 0 :(得分: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);
}