Last active
August 29, 2015 14:27
-
-
Save hello-josh/fb41986a9db511204f59 to your computer and use it in GitHub Desktop.
An alternative idea to the <=> T_SPACESHIP from https://wiki.php.net/rfc/combined-comparison-operator
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
<?php | |
/** | |
* User Getter Sort - Sorts an array using a user defined getter function. | |
* | |
* An imaginary user defined sort alternative where you pass a function that | |
* returns the data that should be used to determine sort order | |
* @param array &$array Array to sort in place | |
* @param Callable $itemfunc The callable that receives the array | |
* item and returns the value that should | |
* be used for sorting | |
*/ | |
function ugsort(&$array, $itemfunc = function($item) {return $item}); | |
// rewrite examples from https://wiki.php.net/rfc/combined-comparison-operator using ugsort | |
// Use case #1 Sort by last name | |
usort($data, function ($left, $right) { | |
return $left[1] <=> $right[1]; | |
}); | |
// ugsort version | |
ugsort($data, function ($item) { | |
return $item[1]; | |
}); | |
// sort by arrays | |
function order_func($a, $b) { | |
return [$a->x, $a->y, $a->foo] <=> [$b->x, $b->y, $b->foo]; | |
} | |
usort(&$array, 'order_func'); | |
// ugsort version | |
ugsort($data, function ($item) { | |
return [$item->x, $item->y, $item->foo]; | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$itemfunc
works similarly tocmp=
in python's sorted