function Array_sort ($array, $key) {if (Is_array ($array)) {$key _array = null; $new _array = null; for ($i = 0; $i < count ( $array); $i + +) {$key _array[$array [$i] [$key]] = $i;} ksort ($key _array); $j = 0; foreach ($key _array as $k = + $v) {$new _array[$j] = $array [$v]; $j + +;} unset ($key _array); return $new _array; }else{return $array;}}
PHP two-dimensional array key value ordering
PHP Array_multisort () can be used to sort multiple arrays at once, or to sort multidimensional arrays based on one dimension or multidimensional. The associated key name remains the same, but the numeric key name is re-indexed. The input array is treated as a column of a table and sorted by rows, and the first array is the primary array to sort. The rows (values) in the array are compared to the same words, sorted by the size of the corresponding values in the next input array, and so on.
But if the array that needs to be sorted is a two-dimensional array that needs to be sorted by the key values of the array, such as the following two-dimensional array, which needs to be sorted by the sort key name, then Array_multisort () cannot be directly implemented:
$data [5] = Array (' volume ' = = ' Edition ' = 2); $data [4] = Array (' volume ' = 1); $data [2] = a Rray (' volume ' = ' Edition ' = 6); $data [3] = Array (' volume ' = 98, ' edition ' = 2); $data [1] = Array (' Volume ' = +, ' Edition ' + 6); $data [6] = Array (' volume ' = =, ' edition ' = 7);//Prepare the array to sort foreach ($data as $k => ; $v) { $edition [] = $v [' edition '];} Array_multisort ($edition, SORT_ASC, $data);p Rint_r ($data);
Will output:
Array ( [0] = = Array ( [Volume] = [ Edition] = 1 ) [1] = = Array ( [ Volume] [ Edition] = 2 ) [2] = = Array ( [Volume] = 98 [Edition] = 2< c14/>) [3] = = Array ( [Volume] = [Edition] = 6 ) [4] = = Array ( [Volume] = [Edition] + 6 ) [5] = = Array ([volume] = [ Edition] = 7 ))
To not destroy the original key, write a sort function that supports only two-dimensional arrays.
/*** is sorted based on the size of one of the key values in the array, supports only two-dimensional arrays * * @param array $array sorted array * @param string $key key value * @p Aram BOOL $ASC The default positive order * @return array sorted after arrays */function Arraysortbykey (array $array, $key, $asc = True) {$result = array (); Sort out the array to be sorted foreach ($array as $k = & $v) {$values [$k] = Isset ($v [$key])? $v [$key]: '; } unset ($v); $ASC do you want to sort the sort key values? Asort ($values): Arsort ($values); Rearrange the original array foreach ($values as $k + = $v) {$result [$k] = $array [$k]; } return $result;}