PHP » Arrays » array_multisort()

Syntax:
bool array_multisort(array array1 [, int order1] [, int sort_type1] [, array array2 [, int order2] [, int sort_type2] , ...])
array1
First "column" to sort by.
order1
Ordering for array1. Can be SORT_ASC or SORT_DESC.
sort_type1
Element evaluation for array1. Can be SORT_REGULAR, SORT_NUMERIC, or SORT_STRING.
array2
Second "column" to sort by.
order2
Ordering for array2.
sort_type2
Element evaluation for array2.

Sorts multiple arrays based on one array.

The array_multisort() function orders the elements in multiple arrays by the values of the first array passed to the function. This is similar to each array being a column in a table sorted by the first column. This function is very flexible with how arguments are passed to it. The first argument has to be an array. After that, ordering and evaluation flags can optionally be specified (either one can come first). Additional arrays with order and evaluation flags can optionally follow. If the array was sorted successfully, TRUE is returned.

Examples

Code:
<?php

$countries = array("Spain", "United Kingdom", "United States", "Sweden", "Italy", "Italy", "United States");
$cities = array("Madrid", "London", "New York", "Stockholm", "Venice", "Rome", "Chicago");
$languages = array("Spanish", "English", "English", "Swedish", "Italian", "Italian", "English");

array_multisort($countries, SORT_ASC, SORT_STRING,
   $cities, SORT_ASC, $languages);

foreach ($countries as $country) {
   print "$country; ";
}
print "<br>";

foreach ($cities as $city) {
   print "$city; ";
}
print "<br>";

foreach ($languages as $language) {
   print "$language; ";
}

?>
Output:
Italy; Italy; Spain; Sweden; United Kingdom; United States; United States;
Rome; Venice; Madrid; Stockholm; London; Chicago; New York;
Italian; Italian; Spanish; Swedish; English; English; English;
Explanation:

A few arrays hold a "table" where each "row" has a country, a city in that country, and a language spoken in that city. The elements are sorted based on country first, then city, and then language. The result is printed one column per line.

See Also: