Created
June 18, 2014 14:48
-
-
Save mikeselander/04160f58748dd73e7b80 to your computer and use it in GitHub Desktop.
Starting point for an expanded array sorting mechanism
From http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php
This file contains hidden or 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
function make_comparer() { | |
// Normalize criteria up front so that the comparer finds everything tidy | |
$criteria = func_get_args(); | |
foreach ($criteria as $index => $criterion) { | |
$criteria[$index] = is_array($criterion) | |
? array_pad($criterion, 3, null) | |
: array($criterion, SORT_ASC, null); | |
} | |
return function($first, $second) use (&$criteria) { | |
foreach ($criteria as $criterion) { | |
// How will we compare this round? | |
list($column, $sortOrder, $projection) = $criterion; | |
$sortOrder = $sortOrder === SORT_DESC ? -1 : 1; | |
// If a projection was defined project the values now | |
if ($projection) { | |
$lhs = call_user_func($projection, $first[$column]); | |
$rhs = call_user_func($projection, $second[$column]); | |
} | |
else { | |
$lhs = $first[$column]; | |
$rhs = $second[$column]; | |
} | |
// Do the actual comparison; do not return if equal | |
if ($lhs < $rhs) { | |
return -1 * $sortOrder; | |
} | |
else if ($lhs > $rhs) { | |
return 1 * $sortOrder; | |
} | |
} | |
return 0; // tiebreakers exhausted, so $first == $second | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment