-3

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

请有人帮助,在此先感谢:)

    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
4

3 回答 3

1

如果小于 ,则传递给 usort 的函数应返回小于零的整数,如果$a小于则返回$b0,如果大于 则返回大于$a == $b0 。$a$b

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

于 2013-10-18T11:03:48.273 回答
0

大致是这样的:

// 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');
于 2013-10-18T11:03:35.573 回答
0

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

用户定义的函数必须返回

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

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

于 2013-10-18T11:04:31.213 回答