Question #6567   Submitted by Answiki on 09/05/2022 at 08:41:15 PM UTC

How to sort a multidimensional array in PHP?

Answer   Submitted by Answiki on 06/11/2020 at 12:04:43 PM UTC

The best way to sort multidimensional arrays in PHP is to use the array_multisort() function.


Let's consider the following PHP array:

$myArray = array(
    array('name' => 'Mick', 'year' => '1976'),
    array('name' => 'Jack', 'year' => '1982'),
    array('name' => 'John', 'year' => '1957')
);
To use the array_multisort() function, you need a single column array containing the index to sort. The following example sort the table by name in ascending order:

$columns = array_column($myArray, 'name');
array_multisort($columns, SORT_ASC, $myArray);
The following example sorts the array by years in descending order:

$columns = array_column($myArray, 'year');
array_multisort($columns, SORT_DESC, $myArray);
The following example sort the array by names in ascending order, then by years in descending order:

$colNames = array_column($myArray, 'name');
$colYears = array_column($myArray, 'year');
array_multisort($colNames, SORT_ASC, $colYears, SORT_DESC, $myArray);


3 events in history
Question by Answiki 09/05/2022 at 08:41:15 PM
How to sort a multidimensional array in PHP?
Answer by Answiki on 06/11/2020 at 12:04:43 PM

The best way to sort multidimensional arrays in PHP is to use the array_multisort() function.


Let's consider the following PHP array:

$myArray = array(
    array('name' => 'Mick', 'year' => '1976'),
    array('name' => 'Jack', 'year' => '1982'),
    array('name' => 'John', 'year' => '1957')
);
To use the array_multisort() function, you need a single column array containing the index to sort. The following example sort the table by name in ascending order:

$columns = array_column($myArray, 'name');
array_multisort($columns, SORT_ASC, $myArray);
The following example sorts the array by years in descending order:

$columns = array_column($myArray, 'year');
array_multisort($columns, SORT_DESC, $myArray);
The following example sort the array by names in ascending order, then by years in descending order:

$colNames = array_column($myArray, 'name');
$colYears = array_column($myArray, 'year');
array_multisort($colNames, SORT_ASC, $colYears, SORT_DESC, $myArray);


Question by Answiki 06/11/2020 at 11:49:17 AM
How to sort a multidimensional arrays by a given key in PHP?
# ID Query URL Count

Icons proudly provided by Friconix.