8

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

例如,我当前的代码:

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

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

usort($array,'lensort');

print_r($array);

输出:

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

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

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

2 回答 2

11

将这两项检查合并到您的比较器中:

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

您可以从这个演示中看到,它会打印:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => AA
    [4] => BB
    [5] => BC
)
于 2013-05-01T00:26:31.397 回答
0

这是另一种方法:

$f = function ($s1, $s2) {
   $n = strlen($s1) <=> strlen($s2);
   if ($n != 0) {
      return $n;
   }
   return $s1 <=> $s2;
};
usort($array, $f);

https://php.net/language.operators.comparison

于 2020-06-21T16:01:40.553 回答