Sometimes we want to sort a multidimensional array, such as the following array:
$a = array(
array(
'age' => 10,
'name' => 'John',
),
array(
'age' => 11,
'name' => 'Jim',
),
array(
'age' => 9,
'name' => 'Tom',
),
);
Copy the code
To sort by age, we use array_multisort(), whose function is
The array in the argument is treated as a table column and sorted BY row – similar to the functionality of the ORDER BY clause in SQL. The first array is the main array to sort. Rows (values) in the array compare identically, sorted by the size of the corresponding value in the next input array, and so on.
So take the age out first:
$age = array();
foreach ($a as $value) {
$age[] = $value['age'];
}
Copy the code
$a = $a;
array_multisort($age, SORT_ASC, $a);
Copy the code
So this is sort a by using an age array to an age array