PHP itself has a function for sorting multi-dimensional arrays.
bool array_multisort ( array $ar1 [, mixed $arg [, mixed $... [, array $... ]]] )
The following is the description of the array_multisort function in the manual:
array_multisort() OK Used to sort multiple arrays at once, or to sort multi-dimensional arrays according to one or more dimensions.
Associated (string) key names remain unchanged, but numeric key names will be re-indexed.
The input array is treated as a table column and sorted by row - this is similar to the functionality of SQL's ORDER BY clause. The first array is the main array to be sorted. If the rows (values) in the array are compared to be the same, they are sorted according to the size of the corresponding value in the next input array, and so on.
From the manual, we can see that PHP's own multi-dimensional sorting is to sort the first array and adjust the subsequent order. An array like this:
array( 'id' => array(1,3,2),
'data'=>array('a','c','b'))
Just Multidimensional sorting by id is enough. But many times, the array we construct is like this:
array(
array('id'=>1,'data'=>'a'),
array('id'=>3, 'data'=>'c'),
array('id'=>2,'data'=>'b')
);
The elements of the array are arranged in rows and need to be sorted by Sort by one column. PHP does not seem to provide a function similar to matrix transposition, so array_multisort cannot be used directly for multidimensional sorting. But you only need to extract the sorted column first and pass it to array_multisort as the first parameter.
function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){ if(is_array($multi_array)){ foreach ($multi_array as $row_array){ if(is_array($row_array)){ $key_array[] = $row_array[$sort_key]; }else{ return -1; } } }else{ return -1; } array_multisort($key_array,$sort,$multi_array); return $multi_array; }