Skip to content

Instantly share code, notes, and snippets.

@bcole808
Created March 5, 2014 17:20
Show Gist options
  • Save bcole808/9371801 to your computer and use it in GitHub Desktop.
Save bcole808/9371801 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
}
};
}
?>
Copy link

ghost commented Jul 13, 2018

Works every time, Thanks!!

@DamirPecnik
Copy link

THANKS!

@yinka-optisoft
Copy link

How to use this pls?

@ThiagoPMaceda
Copy link

thanks man!!!

@sharaz-wpbrigade
Copy link

Thank You man ❤

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment