sort array by length and then alphabetically

后端 未结 3 772
名媛妹妹
名媛妹妹 2020-12-04 02:26

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

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

// to         


        
3条回答
  •  时光说笑
    2020-12-04 03:05

    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.

提交回复
热议问题