Created
March 5, 2014 17:20
-
-
Save bcole808/9371801 to your computer and use it in GitHub Desktop.
Sort a multi-domensional PHP array of objects by key value
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
<?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 | |
} | |
}; | |
} | |
?> |
THANKS!
How to use this pls?
thanks man!!!
Thank You man ❤
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works every time, Thanks!!