Php instance sharing-two-dimensional array sorting-PHP Tutorial

Source: Internet
Author: User
Two-dimensional array sorting for php instance sharing. For PHP, functions such as sort (), asort (), and arsort () can be used to sort one-dimensional arrays. for PHP, the sorting of two-dimensional arrays needs to be customized. The following functions include sort (), asort (), and arsort () for sorting a given two-dimensional array into a one-dimensional PHP array based on the specified key value;

PHP 2D array sorting needs to be customized.

The following function sorts a given two-dimensional array by the specified key value. First, let's look at the function definition:

The code is as follows:


Function array_sort ($ arr, $ keys, $ type = 'asc '){
$ Keysvalue = $ new_array = array ();
Foreach ($ arr as $ k =>$ v ){
$ Keysvalue [$ k] = $ v [$ keys];
}
If ($ type = 'asc '){
Asort ($ keysvalue );
} Else {
Arsort ($ keysvalue );
}
Reset ($ keysvalue );

$ Index = 0; // Save the subscript unchanged with $ k, and the subscript starts from 0 with $ index;
Foreach ($ keysvalue as $ k => $ v ){


$ New_array [$ index] = $ arr [$ k];

$ Index ++;
}
Return $ new_array;
}

It can sort two-dimensional arrays by specified key values, or specify the ascending or descending sort method (the default is ascending). Usage example:

The code is as follows:


$ Array = array (
Array ('name' => 'js', 'date' => '2017-05-01 '),
Array ('name' => 'sh', 'date' => '2017-04-30 '),
Array ('name' => 'BJ ', 'date' => '2017-05-02 ')
);

$ ArrayList = array_sort ($ array, 'date ');
Print_r ($ arrayList );

Sort (), asort (), arsort () and other functions; PHP 2D array sorting needs to be customized. The following function is used to input a given two-dimensional array according to the specified key value...

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.