Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"];

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
509 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...