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

时间:2013-05-01 00:23:56

标签: php arrays sorting

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

例如,我目前的代码:

$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
)

2 个答案:

答案 0 :(得分:11)

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

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

你可以从this demo看到这打印:

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

答案 1 :(得分: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