4.18. Sorting Multiple Arrays
Problem
You want to sort multiple arrays or an array with multiple dimensions.
Solution
Use array_multisort( )
:
To sort multiple arrays simultaneously,
pass multiple arrays to array_multisort( ):
$colors = array('Red', 'White', 'Blue');
$cities = array('Boston', 'New York', 'Chicago');
array_multisort($colors, $cities);
print_r($colors);
print_r($cities);
Array
(
[0] => Blue
[1] => Red
[2] => White
)
Array
(
[0] => Chicago
[1] => Boston
[2] => New York
)To sort multiple dimensions within a single array, pass the specific array elements:
$stuff = array('colors' => array('Red', 'White', 'Blue'),
'cities' => array('Boston', 'New York', 'Chicago'));
array_multisort($stuff['colors'], $stuff['cities']);
print_r($stuff);
Array
(
[colors] => Array
(
[0] => Blue
[1] => Red
[2] => White
)
[cities] => Array
(
[0] => Chicago
[1] => Boston
[2] => New York
)
)
To modify the sort type, as in
sort( ), pass in SORT_REGULAR,
SORT_NUMERIC, or SORT_STRING
after the array. To modify the sort order, unlike in sort( ), pass in SORT_ASC or
SORT_DESC after the array. You can also pass in
both a sort type and a sort order after the array.
Discussion
The array_multisort( ) function can sort several arrays at once or a multidimensional array by one or more dimensions. The arrays are treated as columns of a table to be sorted by rows. The first array is the main one to sort by; all the items in the other arrays are reordered based on the sorted order of the first array. If items ...