Sort php arrays by string length. If you want to analyze the demand: make the search results highly relevant (the results with a large proportion of keywords rank first ). For example, if you search for the keyword "red ",Demand Analysis: make the search results highly correlated (the results with a large proportion of keywords rank first ). For example, if you search for the keyword "red", the sorting of the animation "red" in the results will be greater than that of "Little Red Hat" because of its large keyword ratio. Therefore, a special requirement is raised. a php array is provided, whose content is a string and needs to be re-sorted according to the length of the string. The array functions provided by php can only be sorted in the English order. so google found the solution to use PHP's custom sorting function usort.
- bool usort ( array & $array ,
callback $cmp_function )
In fact, the PHP array sorting by string length is like the bubble sorting method learned in previous computer courses. it accepts two parameters. The first is the array to be sorted, and the second is the callback function, is the sorting condition. Usort is equivalent to a recursion. based on the return value of the condition, it determines whether two adjacent arrays (such as $ a and $ B) are called in reverse order to achieve sorting. If the bubble sorting method is used, the condition is $ a> $ B. Then, if the string length is determined, it is in the format of strlen ($ a)-$ strlen ($ B. You can write the callback function by yourself to complete various strange sorting tasks. Now, CoCo's code can be written as follows:
- $aS = array('aaa', 'aa', 'aaaa', 'aaaaa');
- $F = create_function('$a, $b',
'return(strLen($a) > strLen($b))');
- usort($aS, $F);
We hope that you can fully master this skill by sorting the PHP array by string length through the implementation method described above.
Demand Analysis of keywords: make the search results highly relevant (the results with a large proportion of keywords rank first ). For example, if you search for the keyword "red", the animation "Red" is...