PHP two-dimensional array ordering

Source: Internet
Author: User

For example, an array like the following:

The code is as follows:

$users = Array (
  ' name ' => ' Tom ', ' Age ' =>)
  , Array (' name ' => ' Anny ', ' age ' =>)
  , array (' name ' => ' Jack ', ' age ' =>)
;

Want to be able to sort by age from small to large. The author has collated two methods to come out and share to everybody.

1. Use Array_multisort

Using this method, it is more cumbersome to extract the age out of the one-dimensional array, and then arrange it in ascending order. The specific code is as follows:

The code is as follows:

$ages = Array ();
foreach ($users as $user) {
  $ages [] = $user [' age '];
}
Array_multisort ($ages, SORT_ASC, $users);

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

The code is as follows:

Array_multisort ($ages, SORT_ASC, $names, SORT_ASC, $users);

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.