Example of how to sort multi-dimensional arrays using the PHP function array_multisort ()

Source: Internet
Author: User

ForThe Listing J example illustrates how the PHP function array_multisort () works:

 
 
  1. <?php 
  2. $data = array(array("id" => 1, "name" => "Boney M", "rating" => 3),  
  3. array("id" => 2, "name" => "Take That", "rating" => 1),  
  4. array("id" => 3, "name" => "The Killers", "rating" => 4),  
  5. array("id" => 4, "name" => "Lusain", "rating" => 3),  
  6. ); foreach ($data as $key => $value) {  
  7. $name[$key] = $value['name'];  
  8. $rating[$key] = $value['rating'];  
  9. }  
  10. array_multisort($rating, $name, $data); print_r($data);
  11. ?> 

Here, we simulate an array of rows and columns in the $ data array. Then, I use the PHP function array_multisort () to rearrange the data set. First, sort the data set by rating, and then sort the data by name if rating is equal. The output result is as follows:

Array ([0] => Array

(

[Id] => 2

[Name] => Take That

[Rating] => 1

) [1] => Array

(

[Id] => 1

[Name] => Boney M

[Rating] => 3

)

[2] => Array

(

[Id] => 4

[Name] => Lusain

[Rating] => 3

)

[3] => Array

(

[Id] => 3

[Name] => The Killers

[Rating] => 4

)

)

The PHP function array_multisort () is one of the most useful functions in PHP and has a wide range of applications. In addition, as you can see in the example, it can sort multiple irrelevant arrays, or use one of the elements as the basis for next sorting, you can also sort database result sets.


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.