Created
May 14, 2021 19:57
-
-
Save adityadees/621db0ba5a6138d63ad170577fc3b1b4 to your computer and use it in GitHub Desktop.
PHP SORT MULTIDIMENSIONAL ARRAY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements. | |
usort($myArray, function($a, $b) { | |
$retval = $a['order'] <=> $b['order']; | |
if ($retval == 0) { | |
$retval = $a['suborder'] <=> $b['suborder']; | |
if ($retval == 0) { | |
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder']; | |
} | |
} | |
return $retval; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sortByOrder($a, $b) { | |
return $a['order'] - $b['order']; | |
} | |
usort($myArray, 'sortByOrder'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
usort($myArray, function($a, $b) { | |
return $a['order'] - $b['order']; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
usort($myArray, function($a, $b) { | |
return $a['order'] <=> $b['order']; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment