-
-
Save jtarleton/3b1013a7bec267d1c088 to your computer and use it in GitHub Desktop.
Sort an associative array of objects by any number of properties in any order, maintaining key association.
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 | |
class HelperLibrary | |
{ | |
/** | |
* Sort an associative array of objects by any number of properties in any order, maintaining key association. | |
* | |
* Example usage, for an array of users: | |
* | |
* $users = array(); | |
* | |
* $user = new stdClass; | |
* $user->name = 'John'; | |
* $user->age = 45 | |
* $users['a'] = $user; | |
* | |
* $user = new stdClass; | |
* $user->name = 'Alex'; | |
* $user->age = 20 | |
* $users['b'] = $user; | |
* | |
* $user = new stdClass; | |
* $user->name = 'Alex'; | |
* $user->age = 39 | |
* $users['c'] = $user; | |
* | |
* $user = new stdClass; | |
* $user->name = 'Sarah'; | |
* $user->age = 19 | |
* $users['d'] = $user; | |
* | |
* //Sort users by name ASC, age DESC | |
* HelperLibrary::osort($users, array('name'=>true, 'age'=>false)); | |
* Alex 39 | |
* Alex 20 | |
* John 45 | |
* Sarah 19 | |
* | |
* //Sort users by name DESC, age ASC | |
* HelperLibrary::osort($users, array('name'=>false, 'age'=>true)); | |
* John 45 | |
* Sarah 19 | |
* Alex 20 | |
* Alex 39 | |
* | |
* @author James Tarleton | |
* @param array $array | |
* @param array $props : boolean values for each sort direction, keyed by property name | |
* @return void | |
*/ | |
public static function osort(&$array, array $props) | |
{ | |
$closure = function($a, $b) use ($props) { | |
foreach($props as $prop => $ascending){ | |
if($a->$prop != $b->$prop){ | |
if($ascending){ | |
return strtolower($a->$prop) > strtolower($b->$prop) ? 1 : -1; | |
} else { | |
return strtolower($a->$prop) < strtolower($b->$prop) ? 1 : -1; | |
} | |
} | |
} | |
return -1; //if all props equal | |
}; | |
uasort($array, $closure); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment