目前,我按字符串长度排序数组.但是,当字符串长度相等时,我如何按值排序?
举个例子,我目前的代码:
$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 )
将两个检查合并到比较器中:
原文链接:https://www.f2er.com/php/137858.htmlfunction 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 )