How to sort a multidimensional array in PHP?

Definition

This page explains how to sort a multidimensional array in PHP. This frequently happens when the array is the result of a database query.

The example array

Let's considere the following multidimensional array:

$array[] = array('name' => 'Dupont', 'age' => 72);
$array[] = array('name' => 'Albert', 'age' => 11);
$array[] = array('name' => 'Durand', 'age' => 56);
$array[] = array('name' => 'Michel', 'age' => 52);
$array[] = array('name' => 'Dupont', 'age' => 36);
$array[] = array('name' => 'Plutot', 'age' => 27);
Name Age
Dupont 72
Albert 11
Durand 56
Michel 52
Dupont 36
Plutot 27

Sort by name ascending

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

$columns = array_column($array, 'name');
array_multisort($columns, SORT_ASC, $array);

Here is the result:

Name Age
Albert 11
Dupont 36
Dupont 72
Durand 56
Michel 52
Plutot 27

Sort by age descending

$columns = array_column($array, 'age');
array_multisort($columns, SORT_DESC, $array);

Here is the result:

Name Age
Dupont 72
Durand 56
Michel 52
Dupont 36
Plutot 27
Albert 11

Sort by name ascending, then by age descending

$columns_1 = array_column($array, 'name');
$columns_2 = array_column($array, 'age');
array_multisort($columns_1, SORT_ASC, $columns_2, SORT_DESC, $array);

Here is the result:

Name Age
Albert 11
Dupont 72
Dupont 36
Durand 56
Michel 52
Plutot 27

See also


Last update : 11/25/2021