修改php natcasesort所以'仅限字母'先来

时间:2014-11-14 13:46:23

标签: php arrays sorting

我有一个数组

$arr=array(
"Mega XYZ no number",
"Classic no Number",
"Doppel 80x200cm",
"Classic 100x200cm",
"Mega 240x250",
"Classic 85x200cm",
"Mega 40x250",
"Profi 60x235cm",
"Mega 140x250",
);

并希望订购以下订单:

Classic no Number   
Classic 85x200cm  
Classic 100x200cm    
Doppel 80x200cm  
Mega XYZ no number  
Mega 40x250  
Mega 140x250  
Mega 240x250    
Profi 60x235cm 

php的功能natcasesort()差不多完成它除了Classic no Number'和' Mega XYZ no number'不会成为他们''组中的第一个'!我希望其中没有任何数字的项目出现在按字母顺序排列的数字项目之前。

1 个答案:

答案 0 :(得分:3)

就是这样:

function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    $arr1 = str_split($a);
    $arr2 = str_split($b);

    $number1 = "";
    $number2 = "";

    for($i = 0; $i < count($arr1); $i++){
        $char1 = $arr1[$i];
        $char2 = $arr2[$i];
        if(is_numeric($char1) && !is_numeric($char2)){
            return 1;
        }
        if(!is_numeric($char1) && is_numeric($char2)){
            return -1;
        }
        else if(is_numeric($char1) && is_numeric($char2)){
            $number1 .= $char1;
            $number2 .= $char2;
        }
        else {
            if($char1 != $char2){
                if(!empty($number1) && !empty($number2)){
                    $number1 = intval($number1);
                    $number2 = intval($number2);
                    return ($number1 < $number2) ? -1 : 1;
                }
                return ($char1 < $char2) ? -1 : 1;
            }
            else {
                if(!empty($number1) && !empty($number2) && $number1 != $number2){
                    $number1 = intval($number1);
                    $number2 = intval($number2);
                    return ($number1 < $number2) ? -1 : 1;
                }
            }
        }
    }
}

usort($arr, "cmp");