Php instance sharing-two-dimensional array sorting-php instance

Source: Internet
Author: User
You can use functions such as sort (), asort (), and arsort () to sort PHP one-dimensional arrays. You need to customize the sorting of PHP two-dimensional arrays. You can use functions such as sort (), asort (), and arsort () to sort one-dimensional PHP arrays;

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

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.