且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按长度排序数组,然后按字母顺序排序

更新时间:2023-02-06 14:15:41

您可以将两个条件都放入usort比较函数中.

You can put both of the conditions into a usort comparison function.

usort($array, function($a, $b) {
    return strlen($a) - strlen($b) ?: strcmp($a, $b);
});

按多个条件进行排序的一般策略是为每个条件编写比较表达式,这些条件返回比较函数的适当返回类型(整数,正数,负数或零,具体取决于比较结果),并按照所需的排序顺序对其进行评估,例如首先是长度,然后是字母顺序.

The general strategy for sorting by multiple conditions is to write comparison expressions for each of the conditions that returns the appropriate return type of the comparison function (an integer, positive, negative, or zero depending on the result of the comparison), and evaluate them in order of your desired sort order, e.g. first length, then alphabetical.

如果一个表达式的计算结果为零,则在该比较方面两项是相等的,应评估下一个表达式.如果不是,则可以将该表达式的值作为比较函数的值返回.

If an expression evaluates to zero, then the two items are equal in terms of that comparison, and the next expression should be evaluated. If not, then the value of that expression can be returned as the value of the comparison function.

此处的另一个答案似乎暗示此比较函数不会返回大于,小于或等于零的整数.是的.

The other answer here appears to be implying that this comparison function does not return an integer greater than, less than, or equal to zero. It does.