PHP sort array alphabetically then numerically?

前端 未结 4 1787
忘掉有多难
忘掉有多难 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条回答
  •  旧时难觅i
    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

提交回复
热议问题