Sort using "create_function" comparator in PHP prior to 5.3?
anonymous-function, php, sorting
Solution
You could do like this:
Class Sorter {
private $key;
public function __construct($key) {
$this->key = $key;
}
public function sort($a, $b) {
return strnatcmp($a[$this->key], $b[$this->key]);
}
}
usort($numTurnsPerUser, array(new Sorter('key_b'), 'sort'));
Problem
I have never used anonymous functions in PHP before, but I found a piece of code that uses one in order to sort objects ``` usort($numTurnsPerUser,build_sorter('turns')); function build_sorter($key) { return function ($a, $b) use ($key) { return strnatcmp($a[$key], $b[$key]); }; } ``` This code will sort an object by a key (I pass in "turns"). For example, an object that looks like this: (written in JSON, just for readability) ``` $numTurnsPerUser = { "31":{ "turns":15, "order":0 }, "36":{ "turns":12, "order":1 }, "37":{ "turns":14, "order":2 } } ``` will be sorted into an object that looks like this: ``` $numTurnsPerUser = { "36":{ "turns":12, "order":1 }, "37":{ "turns":14, "order":2 }, "31":{ "turns":15, "order":0 } } ``` This worked great on my local server, which is running PHP 5.3.0, but it fails to work on my online server, which is running "php5" - I'm unable to find any information other than that. I am getting an error Parse error: syntax error, unexpected T_FUNCTION I read that PHP < 5.3 cannot use anonymous functions and must use create_function, but the "use" part of the anonymous function has me stumped. Could someone please explain to me what that "use" part of the function is, or better yet, how I can "translate" this to the create_function parameters needed?