How to use PHP function Usort () to implement custom sorting _php tutorials

Source: Internet
Author: User
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:

 
 
    1. !--? php
    2. $ data = Span class= "Attribute-value" >array ("joe@host.com", "john.doe@gh.co.uk",
      "Asmithsonian@us.info", " Jay@zoo.tw "); Usort ($data, ' Sortbylen ');
    3. Print_r ($data), function Sortbylen ($a, $b) {
    4. < Span>if (strlen ($a) = = strlen ($b)) {
    5. return 0;
    6. } else {
    7. return (strlen ($a) ; strlen ($b))? 1:-1;
    8. }
    9. }
    10. ?

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 ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.