如何按字符串长度排序数组,然后按PHP中的值排序?

时间:2023-01-31 07:29:06

Currently, I have my array sorting by string length. But, when the string lengths are equal, how do I sort by value?

目前,我按字符串长度排序数组。但是,当字符串长度相等时,我如何按值排序?

As an example, my current code:

举个例子,我目前的代码:

$array = array("A","BC","AA","C","BB", "B");

function lensort($a,$b){
    return strlen($a)-strlen($b);
}

usort($array,'lensort');

print_r($array);

Outputs:

输出:

Array
(
    [0] => C
    [1] => A
    [2] => B
    [3] => BB
    [4] => AA
    [5] => BC
)

But, I'd like it to sort by the following instead:

但是,我希望它按以下方式排序:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)

1 个解决方案

#1


11  

Incorporate both checks into your comparator:

将两个检查合并到比较器中:

function lensort($a,$b){
    $la = strlen( $a); $lb = strlen( $b);
    if( $la == $lb) {
        return strcmp( $a, $b);
    }
    return $la - $lb;
}

You can see from this demo that this prints:

您可以从此演示中看到此打印:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)

#1


11  

Incorporate both checks into your comparator:

将两个检查合并到比较器中:

function lensort($a,$b){
    $la = strlen( $a); $lb = strlen( $b);
    if( $la == $lb) {
        return strcmp( $a, $b);
    }
    return $la - $lb;
}

You can see from this demo that this prints:

您可以从此演示中看到此打印:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)