Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sharaz-wpbrigade/62bb2e8de1b79ace92cae5e63377b982 to your computer and use it in GitHub Desktop.
Save sharaz-wpbrigade/62bb2e8de1b79ace92cae5e63377b982 to your computer and use it in GitHub Desktop.
Sort a multi-domensional PHP array of objects by key value
<?php
/**
* Sort a multi-domensional array of objects by key value
* Usage: usort($array, arrSortObjsByKey('VALUE_TO_SORT_BY'));
* Expects an array of objects.
*
* @param String $key The name of the parameter to sort by
* @param String $order the sort order
* @return A function to compare using usort
*/
function arrSortObjsByKey($key, $order = 'DESC') {
return function($a, $b) use ($key, $order) {
// Swap order if necessary
if ($order == 'DESC') {
list($a, $b) = array($b, $a);
}
// Check data type
if (is_numeric($a->$key)) {
return $a->$key - $b->$key; // compare numeric
} else {
return strnatcasecmp($a->$key, $b->$key); // compare string
}
};
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment