Php two-dimensional array sorting methods

Source: Internet
Author: User
Php two-dimensional array sorting methods

  1. $ Users = array (
  2. Array ('name' => 'Tom ', 'age' => 20)
  3. , Array ('name' => 'anny ', 'age' => 18)
  4. , Array ('name' => 'Jack', 'age' => 22)
  5. );

We hope to sort data by age size from small to large.

The following two methods are provided for your reference.

1. use array_multisort

Using this method will be more troublesome. you need to extract the age and store it in a one-dimensional array, and then sort it in ascending order by age. The code is as follows:

  1. $ Ages = array ();
  2. Foreach ($ users as $ user ){
  3. $ Ages [] = $ user ['age'];
  4. }
  5. Array_multisort ($ ages, SORT_ASC, $ users );

After Execution, $ users is the sorted array. you can print it out. If you need to sort by age in ascending order and then by name in ascending order, the method is the same as above, that is, to extract an array of names, the final sorting method is called as follows: array_multisort ($ ages, SORT_ASC, $ names, SORT_ASC, $ users );

2. use usort

The biggest advantage of using this method is that you can customize some complicated sorting methods. For example, sort by name length in descending order:

  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. });

The anonymous function is used here. if necessary, it can be extracted separately. $ A and $ B can be understood as elements in the $ users array. you can directly index the name value, calculate the length, and then compare the length. We recommend that you use the second method because the steps for extracting the Sorted content to one-dimensional arrays are missing and the sorting method is more flexible.

>>> For more information, see The php array sorting method <

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.