This article introduces the code for grouping and sorting php two-dimensional arrays. For more information, see. This article introduces the code for grouping and sorting php two-dimensional arrays. For more information, see.
Script ec (2); script
Group sorting
| The Code is as follows: |
|
|
$ New2 ['group'] ['key'] = 'time ';
$ New ['a'] ['B'] = 44;
$ New ['a'] ['C'] = 33;
$ New ['a'] ['D'] = 34;
$ New ['bb'] ['B'] = 55;
$ New ['bb'] ['C'] = 32;
$ New ['cc'] ['4'] = 77;
$ New ['dd'] ['G'] = 55;
$ New ['dd'] ['C'] = 54;
Function arr_group_sort ($ new ){
Foreach ($ new as $ key => $ val ){
Asort ($ new [$ key]); // sort the data in each group;
$ Tmp = $ new [$ key]; // assign the sorted data to a temporary array;
$ Tmp [] = $ key; // Add the key value of the original array to the end of the temporary array to prepare for the subsequent modification of the key value;
$ A = array_shift ($ new [$ key]); // extract the first (minimum) data of each group. Take the aa group as an example, $ a: The value is 33;
$ Aa [$ a] = $ tmp; // create an array with $ aa (for example, 33) as the key value;
Ksort ($ aa); // sort by key value
}
Foreach ($ aa as $ key => $ val) {// array sorted by key value, which has lost the original key value, for example, aa/bb/cc/dd. Fortunately, we have saved the key value to the end of the temporary array;
$ B = array_pop ($ aa [$ key]); // obtain the key value;
$ Bb [$ B] = $ aa [$ key]; // create an array and use the previous key value (aa/bb/cc)
}
Return $ bb; // return
}
$ C = arr_group_sort ($ new );
Print_r ($ new); // original array;
Print_r ($ c); // array After grouping;
?> |
Other two-dimensional array sorting methods
| 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 );
Foreach ($ keysvalue as $ k => $ v ){
$ New_array [$ k] = $ arr [$ k];
}
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' => 'phone', 'brand' => 'nokia ', 'price' => 1050 ),
Array ('name' => 'laptop ', 'brand' => 'lenovo', 'price' => 4300 ),
Array ('name' => 'shares', 'brand' => 'phillips', 'price' => 3100 ),
Array ('name' => 'treadmill ', 'brand' => 'three', 'price' => 4900 ),
Array ('name' => 'Watch ', 'brand' => 'case', 'price' => 960 ),
Array ('name' => 'LCD TV', 'brand' => 'sony ', 'price' => 6299 ),
Array ('name' => 'laser printer ', 'brand' => 'hp', 'price' => 1200)
);
$ ShoppingList = array_sort ($ array, 'price ');
Print_r ($ ShoppingList ); |