We have discussed various php array sorting methods before, and php also provides a large number of data sorting functions, such as sort (), asort (), and arsort, next, I will introduce you to the method for sorting two-dimensional arrays by specified key values.
Specific instance
The Code is as follows: |
Copy code |
/* Sort two-dimensional arrays by specified key values */ Function array_sort ($ array, $ keys, $ type = 'asc '){ If (! Isset ($ array) |! Is_array ($ array) | empty ($ array )){ Return ''; } If (! Isset ($ keys) | trim ($ keys) = ''){ Return ''; } If (! Isset ($ type) | $ type = ''|! In_array (strtolower ($ type), array ('asc ', 'desc '))){ Return ''; } $ Keysvalue = array (); Foreach ($ array as $ key => $ val ){ $ Val [$ keys] = str_replace ('-', '', $ val [$ keys]); $ Val [$ keys] = str_replace ('','', $ val [$ keys]); $ Val [$ keys] = str_replace (':', '', $ val [$ keys]); $ Keysvalue [] = $ val [$ keys]; } Asort ($ keysvalue); // sort key values Reset ($ keysvalue); // The Pointer Points to the first array. Foreach ($ keysvalue as $ key => $ vals ){ $ Keysort [] = $ key; } $ Keysvalue = array (); $ Count = count ($ keysort ); If (strtolower ($ type )! = 'Asc '){ For ($ I = $ count-1; $ I> = 0; $ I --){ $ Keysvalue [] = $ array [$ keysort [$ I]; } } Else { For ($ I = 0; $ I <$ count; $ I ++ ){ $ Keysvalue [] = $ array [$ keysort [$ I]; } } Return $ keysvalue; } |
Usage:
For example:
The Code is as follows: |
Copy code |
$ A = array ( 1 => array ( Id => 1, Price => '79 ', ), 2 => array ( Id => 1, Price => '68 ', ), );
|
Use:
The Code is as follows: |
Copy code |
Array_sort ($ a, 'price '); |
Php array sorting Function
Sort (& $ arr [, fruits]) sorts the array from low to high, and assigns a new key name to return bool bKjia. c0m
Rsort (& $ arr [, fruits]) sorts the array in reverse order and assigns a new key name.
Asort (& $ arr [, fruits]) sorts arrays and keeps indexes unchanged.
Arsort (& $ arr [, fruits]) sorts arrays in reverse order and keeps indexes unchanged.
Ksort (& $ arr [, fruits]) sorts arrays by key name.
Krsort (& $ arr [, fruits]) sorts the number of groups by key name in reverse order.
Natsort (& $ arr) sorts the array key values by 'natural sorted' and letters by length.
Natcasesort (& $ arr) performs a case-insensitive 'natural ranking' on the array'
Usort (& $ arr, cmp_function) User-Defined Function sorts an array and resorts the key names
Uksort (& $ arr, cmp_function) User-Defined Function sorts an array by key name
Uasort (& $ arr, cmp_function) User-Defined Function sorts the array and keeps the index unchanged
Array_multisort ($ arr, mixed)
The second parameter indicates that the sorting behavior can be changed based on the value.
SORT_REGULAR normal comparison Unit SORT_NUMERIC www. bKjia. c0m is compared as a number.
The SORT_STRING unit is used as a string to compare SROT_LOCALE_STRING. Based on the current local settings, the unit is used as a string for comparison.