PHP two-dimensional array ordering method (Array_multisort usort function)

Source: Internet
Author: User
    1. $users = Array (
    2. Array (' name ' = ' Tom ', ' age ' = 20)
    3. , Array (' name ' = ' Anny ', ' age ' = 18)
    4. , Array (' name ' = ' Jack ', ' age ' = 22)
    5. );
Copy Code

I want to be able to sort by age from small to large.

Method 1, use Array_multisort to extract the age to be stored in a one-dimensional array, and then in ascending order of age. Code:

    1. $ages = Array ();
    2. foreach ($users as $user) {
    3. $ages [] = $user [' Age '];
    4. }
    5. Array_multisort ($ages, SORT_ASC, $users);
Copy Code

After execution, $users is a sorted array and can be printed out to see. If you need to first sort by age, and then by name in ascending order, the same way, is to extract an array of names, the final sorting method to call:

    1. Array_multisort ($ages, SORT_ASC, $names, SORT_ASC, $users);
Copy Code

Method 2, using Usort This method allows you to customize some of the more complex sorting methods.

For example, sort by name in descending order of length:

    1. Usort ($users, function ($a, $b) {
    2. $al = strlen ($a [' name ']);
    3. $BL = strlen ($b [' name ']);
    4. if ($al = = $BL)
    5. return 0;
    6. Return ($al > $bl)? -1:1;
    7. });
Copy Code

Anonymous functions are used here and can be extracted separately if necessary. A $ A, $b can be understood as an element under the $users array, you can directly index the name value, calculate the length, and then compare the length.

The second method is recommended because fewer steps are taken to extract the sorted content into a one-dimensional array, and the ordering method is more flexible.

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