Home > Article > Backend Development > Sort PHP arrays according to string length_PHP tutorial
If you want to analyze needs: let the search results be highly relevant (results with a large proportion of keywords are ranked first). For example, if you search for the keyword "red", then the animation "Red" will be ranked higher in the results than "Little Red Riding Hood" because its keyword ratio is large. So a special requirement arose. Given a PHP array, the contents are all strings, and they need to be sorted again according to the length of the strings. The array functions provided by PHP can only be sorted in English order, so I googled and found the solution, which is to use PHP's custom sorting function usort.
<ol class="dp-xml"><li class="alt"><span><span>bool usort ( array & $array ,<br> callback $cmp_function ) </span></span></li></ol>
In fact, the method of sorting PHP arrays by string length is like the bubble sort 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 condition for sorting. Usort is equivalent to a recursion, which determines whether to swap two adjacent arrays (such as $a, $b) based on the return value of the condition to achieve the purpose of sorting. If based on the bubble sorting method, this condition is $a>$b. So if it is based on the length of the string, then it is in the format of strlen($a)-$strlen($b). By writing your own callback function, you can complete all kinds of weird sorting. Then, CoCo’s current code can be written like this:
<ol class="dp-xml"> <li class="alt"><span><span>$</span><span class="attribute">aS</span><span> = </span><span class="attribute-value">array</span><span>('aaa', 'aa', 'aaaa', 'aaaaa'); </span></span></li> <li> <span>$</span><span class="attribute">F</span><span> = </span><span class="attribute-value">create_function</span><span>('$a, $b', <br>'return(strLen($a) </span><span class="tag">></span><span> strLen($b))'); </span> </li> <li class="alt"><span>usort($aS, $F); </span></li> </ol>
I hope that through the implementation method of sorting PHP arrays by string length introduced above, everyone can fully master this technique.