Skip to content

Instantly share code, notes, and snippets.

@adityadees
Created May 14, 2021 19:57
Show Gist options
  • Save adityadees/621db0ba5a6138d63ad170577fc3b1b4 to your computer and use it in GitHub Desktop.
Save adityadees/621db0ba5a6138d63ad170577fc3b1b4 to your computer and use it in GitHub Desktop.
PHP SORT MULTIDIMENSIONAL ARRAY
// 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;
});
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
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