2013-10-18 58 views
-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 
+3

按長度排序字符串數組;如果字符串的長度相同,則按字母順序排序......所以問題是什麼? –

+0

該功能的哪一部分讓你感到困惑?只有5行,他們沒有任何複雜。 – Barmar

+1

「我很欣賞這些迴應,但我希望如果有人能夠編寫代碼來完成同樣的任務,而不是使用內置函數」 - 這不是一個合適的SO請求。 –

回答

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'); 
1

功能傳遞給usort預計將返回一個整數小於零,如果$a小於$b如果$a == $b爲0,並且如果$a大於$b則大於0。

在這種情況下,它使用$la - $lb,因爲這將返回基於$a$b長度差異的適當整數。如果長度相同,則使用strcmp,這也將返回一個適當的整數。

0

usort函數使用用戶定義的比較函數按值排序給定的數組。

用戶定義的函數必須返回

  • 0,如果它的參數是等於小於零
  • 整數值,如果它的第一個參數是小於第二
  • 整數大於零的值,如果它的第一參數大於秒

在您的代碼片段中,此用戶定義的比較函數是lensort,它將給定的字符串與它們的l進行比較engths。