Two-dimensional arrays are often used in PHP development, but their sorting is not as convenient as using built-in functions as one-dimensional arrays, the following describes in detail the two-dimensional arrays that are frequently encountered in PHP development, but their sorting is not as convenient as the one-dimensional array using built-in functions, to sort two-dimensional arrays, we need to write our own function. here, UncleToo will share with you a function for sorting two-dimensional arrays in PHP:
Code:
The code is as follows:
Functionarray_sort ($ arr, $ keys, $ type = 'asc '){
$ Keysvalue = $ new_array = array ();
Foreach ($ arras $ k => $ v ){
$ Keysvalue [$ k] = $ v [$ keys];
}
If ($ type = 'asc '){
Asort ($ keysvalue );
} Else {
Arsort ($ keysvalue );
}
Reset ($ keysvalue );
Foreach ($ keysvalueas $ k => $ v ){
$ New_array [$ k] = $ arr [$ k];
}
Return $ new_array;
}
Three parameters of the function are described as follows:
$ Arr: array to be sorted
$ Keys: specifies the key value to sort.
$ Type: sorting method, in ascending or descending order. the default value is ascending.
This PHP function can sort a two-dimensional array by the specified key value and return the sorted array.
Call example:
The code is as follows:
$ NewArray = array_sort ($ array, 'price ');
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