请解释以下排序功能


Please explain the following sorting function

此函数按元素大小的递增顺序对数组进行排序,如果大小相等,则根据字典顺序进行排序。

请有人帮忙,提前谢谢:)

    function lensort($a,$b){
    $la = strlen( $a); 
    $lb = strlen( $b);
    if( $la == $lb) {
        return strcmp( $a, $b);
    }
    return $la - $lb;
}
usort($array,'lensort');
 I appreciate the responses, but i want if someone can just write a code to do the same task, not using inbuilt function
传递给 usort 的函数如果小于 $b,则返回小于零的整数,如果$a == $b则返回 0,如果

$a大于 $b$a则返回大于 0 的整数。

在这种情况下,它使用 $la - $lb因为这将根据 $a$b 的长度差异返回一个合适的整数。如果长度相同,则使用 strcmp 这也将返回一个适当的整数。

大致是这样的:

// declare the function
function lensort($a,$b){
// Set $LA to the length of string $a
$la = strlen( $a); 
// Set $Lb to the length of string $b
$lb = strlen( $b);
// If both strings are of equal length
if( $la == $lb) {
   // Return a neg or pos number based on which of the two strings is larger, alfabetically seen
    return strcmp( $a, $b);
}
// If not the same length, just return the size of one minus the other
return $la - $lb;
}
// Use usort to perform a person function-based sorting routine on the input data.
usort($array,'lensort');

usort函数使用用户定义的比较函数按值对给定数组进行排序。

用户定义的函数必须返回

  • 如果参数相等,则为 0
  • 如果第一个参数小于第二个参数,则整数值小于零
  • 如果第一个参数大于第二个参数,则为大于零的整数值

在你的代码片段中,这个用户定义的比较函数是lensort的,它按长度比较给定的字符串。