按长度排序数组,然后按字母顺序排序 [英] sort array by length and then alphabetically

查看:80
本文介绍了按长度排序数组,然后按字母顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一种方法,先按长度排序单词,然后按字母顺序排序.

I'm trying to make a way to sort words first by length, then alphabetically.

// from
$array = ["dog", "cat", "mouse", "elephant", "apple"];

// to
$array = ["cat", "dog", "apple", "mouse", "elephant"];

我已经看到此答案,但这是Java语言,并且此答案 ,但仅处理按长度排序.我尝试使用答案中提供的代码按长度排序,然后按字母顺序排序,但随后仅按字母顺序排序.

I've seen this answer, but it's in Java, and this answer, but it only deals with the sorting by length. I've tried sorting by length, using the code provided in the answer, and then sorting alphabetically, but then it sorts only alphabetically.

如何首先按长度排序,然后按字母顺序排序?

How can I sort it first by length, and then alphabetically?

推荐答案

您可以将两个条件都放入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.

这篇关于按长度排序数组,然后按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆