I have an array sorting function as follows:
public function sortAscending($accounts)
{
function ascending($accountA, $accountB) {
if ($accountA['AmountUntilNextTarget'] == $accountB['AmountUntilNextTarget']) {
return 0;
}
return ($accountA['AmountUntilNextTarget'] < $accountB['AmountUntilNextTarget']) ? -1 : 1;
}
usort($accounts, $ascending);
return $accounts;
}
Clearly this is not ideal as it is hard-coding the key to search for. I thought I would make this generic by passing the key as a param to outside function, however this is then out-of-scope in the inner function. I tried to get around this by using a closure, which would have access to the param, instead of an inner function as follows:
public function sortAscending($accounts, $key)
{
$ascending = function($accountA, $accountB) {
if ($accountsA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] < $accountB[$key]) ? -1 : 1;
}
usort($accounts, $ascending);
return $accounts;
}
However usort() only accepts a function name, so this doesn't work. Can anyone see a (better?) way of achieving this?
usort
accepts acallback
parameter, which can be a closure. The obvious error in your code is the missing;
after the function definition. Maybe that is the cause of the error. – Applesauce;
,$key
is also not in the scope of your closure. You should use it:$ascending = function($acciontA, $accountB) use($key) { ..
. – Claustrophobia