PHP two-dimensional array sorting methods

Source: Internet
Author: User

What we will introduce to you today is aboutThe following describes the array_multisort function in the manual:

Array_multisort () can be used to sort multiple PHP two-dimensional arrays at a time, or sort multi-dimensional arrays by one or more dimensions.

The Association (string) key name remains unchanged, but the number key name is re-indexed.

The input array is treated as a table column and sorted BY rows-similar to the SQL ORDER BY clause. The first array is the main array to be sorted. If the rows (values) in the array are the same, they are sorted by the corresponding values in the next input array.

From the manual, we can see that PHP 2D array sorting is based on the first array, and the subsequent order is adjusted. Arrays like this:

 
 
  1. array( 'id' => array(1,3,2),  
  2.           'data'=>array('a','c','b')) 

You only need to sort by id in multiple dimensions. However, in many cases, the arrays we construct are as follows:

 
 
  1. array(  
  2.             array('id'=>1,'data'=>'a'),  
  3.             array('id'=>3,'data'=>'c'),  
  4.             array('id'=>2,'data'=>'b')  
  5.         );  

Elements in the PHP two-dimensional array sorting are arranged in rows and must be sorted by one of the columns. PHP does not seem to provide functions similar to matrix transpose. Therefore, you cannot directly use array_multisort for multi-dimensional sorting. However, you only need to extract the sorted columns and pass them to array_multisort as the first parameter.


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.