Sorting two-dimensional arrays based on a key value is a common problem. Here we will summarize a function to sort the two key values separately. If you want more values, you can solve them by yourself.
However, if the array to be sorted is a two-dimensional array, it needs to be sorted by the key value of the array. For example, the following two-dimensional array needs to be sorted by sort key name, then array_multisort () it cannot be implemented directly:
Instance 1,
The code is as follows: |
Copy code |
$ Arr = array ( Array ( 'Sort '=> 3, 'A' => 'A ', 'B' => 'B' ), Array ( 'Sort '=> 5, 'A' => 'A ', 'B' => 'B' ), Array ( 'Sort '=> 1, 'A' => 'A ', 'B' => 'B' ) );
|
In this case, array_multisort () cannot take effect,
We can upgrade the function and sort it according to the specified key value.
The code is as follows: |
Copy code |
Function array_sort ($ arr, $ key1, $ sort1 = 'asc ', $ key2 = '', $ sort2 = 'asc '){ If (! Is_array ($ arr )){ Return $ arr; } Foreach ($ arr AS $ key => $ row ){ $ Temp [$ key] = $ row [$ key1]; } $ Sort1 = $ sort1 = 'asc '? SORT_ASC: SORT_DESC; If (! $ Key2 ){ Array_multisort ($ temp, $ sort1, $ arr ); } Else { Foreach ($ arr AS $ key => $ row ){ $ Temp2 [$ key] = $ row [$ key2]; } $ Sort2 = $ sort2 = 'asc '? SORT_ASC: SORT_DESC; Array_multisort ($ temp, $ sort1, $ temp2, $ sort2, $ arr ); } Return $ arr; } |
Instance 2
The code is as follows: |
Copy code |
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; }
$ 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 ); |
The plane sorts the two-dimensional array $ array in descending order of 'price.