Skip to content

Instantly share code, notes, and snippets.

@mtougeron
Created January 27, 2012 21:47
Show Gist options
  • Save mtougeron/1691105 to your computer and use it in GitHub Desktop.
Save mtougeron/1691105 to your computer and use it in GitHub Desktop.
arrayMultiSort
public static function arrayMultiSort(array &$array, array $sortFields, $phpCompareMethod = 'strnatcasecmp')
{
if ( count($sortFields) == 0 ) {
throw new Exception('Missing fields to sort by');
} elseif ( empty($array) || count($array) == 1 ) {
// We return true because "technically" the sort succeeded even though
// we didn't really sort anything. aka it didn't fail so it must be successful
return true;
}
if ( !function_exists($phpCompareMethod) ) {
throw new Exception("$phpCompareMethod is not a valid function");
}
$compareFields = array();
foreach ($sortFields as $fieldName => $sortDirection) {
if ($sortDirection === SORT_DESC) {
$compareFields[] = array('fieldName' => $fieldName, 'sortValue' => -1);
} else {
$compareFields[] = array('fieldName' => $fieldName, 'sortValue' => 1);
}
}
// Closure method to pass to uasort
$compareFunction = function($a, $b, $idx = 0) use (&$compareFunction, $compareFields, $phpCompareMethod) {
$returnValue = $compareFields[$idx]['sortValue'] * @$phpCompareMethod($a[$compareFields[$idx]['fieldName']], $b[$compareFields[$idx]['fieldName']]);
if ( $returnValue == 0 && $idx < (count($compareFields) - 1) ) {
return $compareFunction($a, $b, ($idx+1));
}
return $returnValue;
};
return uasort($array, $compareFunction);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment