Pre-recorded question

Question #71
How to sort a multidimensional arrays by a given key in PHP?
Answer

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);


2 events in history
Answer by Alphonsio 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 Alphonsio 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.