PHP sort array alphabetically then numerically?

前端 未结 4 1760
忘掉有多难
忘掉有多难 2020-12-06 16:46

I have an array..

$test = array(\"def\", \"yz\", \"abc\", \"jkl\", \"123\", \"789\", \"stu\");

if I run sort() on it I get

相关标签:
4条回答
  • 2020-12-06 17:25

    You could do this using usort and a custom comparison function, but this sounds like more trouble than it's worth. I'd use sort, and then handle that output accordingly. It's not clear how you want to use it, but a simple way might be:

    sort($test);
    foreach ($test as $index=>$value) {
        if (is_numeric($value)) {
           $test[] = $value;
           unset($test[$index]);
        } else {
            continue;
        }
    }
    

    usort will probably be faster and it's going to do the comparisions once, while the other solutions mentioned thus far may be a little slower as they require iterating over some or all of the array before or after the sort

    0 讨论(0)
  • 2020-12-06 17:36

    In the following code is separate the data in two arrays: one is numerical the other is not and sort it and merge it.

    $arr1 = $arr2 = array();
    
    $foreach ($arr as $val) {
    
    if (is_numeric($val)) {array_push($arr2, $val); } 
    else {array_push($arr1, $val);}
    
    } 
    

    so you have to separate arrays whit numeric and non-numeric

    sort($arr2);
    sort($arr1);
    
    $test = array_merge($arr2,$arr1);
    
    0 讨论(0)
  • 2020-12-06 17:40

    What you need is sort but with a custom comparison function (usort). The following code will get it done:

    function myComparison($a, $b){
        if(is_numeric($a) && !is_numeric($b))
            return 1;
        else if(!is_numeric($a) && is_numeric($b))
            return -1;
        else
            return ($a < $b) ? -1 : 1;
    } 
    $test = array("def", "yz", "abc", "jkl", "123", "789", "stu");
    usort ( $test , 'myComparison' );
    
    0 讨论(0)
  • 2020-12-06 17:49

    You could convert your numbers to integers before sorting:

    $array = array("def", "yz", "abc", "jkl", "123", "789", "stu");
    
    foreach ($array as $key => $value) {
        if (ctype_digit($value)) {
            $array[$key] = intval($value);
        }
    }
    
    sort($array);
    print_r($array);
    

    Output:

    Array
    (
      [0] => abc
      [1] => def
      [2] => jkl
      [3] => stu
      [4] => yz
      [5] => 123
      [6] => 789
    )
    
    0 讨论(0)
提交回复
热议问题