There are many ways to sort arrays in, including sorting by value, sorting by keywords, natural language sorting, and so on. What we're going to teach you today is to implement a custom array ordering using PHP function Usort (). You can create your own comparison function and pass it to PHP function Usort (), if the first argument is smaller than the second argument, the comparison function must return a number smaller than 0, and if the first argument is "large" than the second argument, the comparison function should return a number greater than 0.
Listing I is an example of the PHP function Usort (), in this example, according to their length of the array elements are sorted, the shortest item is placed at the front:
- !--? php
- $ data = Span class= "Attribute-value" >array ("joe@host.com", "john.doe@gh.co.uk",
"Asmithsonian@us.info", " Jay@zoo.tw "); Usort ($data, ' Sortbylen ');
- Print_r ($data), function Sortbylen ($a, $b) {
- < Span>if (strlen ($a) = = strlen ($b)) {
- return 0;
- } else {
- return (strlen ($a) ; strlen ($b))? 1:-1;
- }
- }
- ?
This creates our own comparison function, which uses the PHP function Usort () to compare the number of each string, and then returns 1,0 or-1, respectively. This return value is the basis for determining the arrangement of elements. Here is the result of its output:
Array ([0] = jay@zoo.tw
[1] = joe@host.com
[2] = john.doe@gh.co.uk
[3] = Asmithsonian@us.info
)
I hope you can use this sample code to learn the specific usage of PHP function Usort ().
http://www.bkjia.com/PHPjc/446347.html www.bkjia.com true http://www.bkjia.com/PHPjc/446347.html techarticle There are many ways to sort arrays in, including sorting by value, sorting by keywords, natural language sorting, and so on. What we are going to teach you today is to use PHP function Usort () to actually ...