How to sort a multidimensional array in PHP?
The best way to sort multidimensional arrays in PHP is to use the array_multisort()
function.
Let's consider the following PHP array:
To use the $myArray = array(
array('name' => 'Mick', 'year' => '1976'),
array('name' => 'Jack', 'year' => '1982'),
array('name' => 'John', 'year' => '1957')
);
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:
The following example sorts the array by years in descending order:$columns = array_column($myArray, 'name');
array_multisort($columns, SORT_ASC, $myArray);
The following example sort the array by names in ascending order, then by years in descending order:$columns = array_column($myArray, 'year');
array_multisort($columns, SORT_DESC, $myArray);
$colNames = array_column($myArray, 'name');
$colYears = array_column($myArray, 'year');
array_multisort($colNames, SORT_ASC, $colYears, SORT_DESC, $myArray);
The best way to sort multidimensional arrays in PHP is to use the array_multisort()
function.
Let's consider the following PHP array:
To use the $myArray = array(
array('name' => 'Mick', 'year' => '1976'),
array('name' => 'Jack', 'year' => '1982'),
array('name' => 'John', 'year' => '1957')
);
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:
The following example sorts the array by years in descending order:$columns = array_column($myArray, 'name');
array_multisort($columns, SORT_ASC, $myArray);
The following example sort the array by names in ascending order, then by years in descending order:$columns = array_column($myArray, 'year');
array_multisort($columns, SORT_DESC, $myArray);
$colNames = array_column($myArray, 'name');
$colYears = array_column($myArray, 'year');
array_multisort($colNames, SORT_ASC, $colYears, SORT_DESC, $myArray);
# | ID | Query | URL | Count |
---|