I have this function in my old php5 code that will accept a variable number of parameters and perform sorting based on the parameters:
function array_alternate_multisort(){
$arguments = func_get_args();
$arrays = $arguments[0];
for ($c = (count($arguments)-1); $c > 0; $c--)
{
if (in_array($arguments[$c], array(SORT_ASC , SORT_DESC)))
{
continue;
}
$compare = create_function('$a,$b','return strcasecmp($a["'.$arguments[$c].'"], $b["'.$arguments[$c].'"]);');
usort($arrays, $compare);
if ($arguments[$c+1] == SORT_DESC)
{
$arrays = array_reverse($arrays);
}
}
return $arrays ;
}
I call it like this:
$alliances = array_alternate_multisort($alliances, "output", SORT_DESC, "score", SORT_DESC);
How can I replace this with a function without calling create_function()
?
You can use an anonymous function instead:
$compare = function ($a, $b) use ($arguments, $c) {
return strcasecmp($a[$arguments[$c]], $b[$arguments[$c]]);
};
Untested but should be close enough
The use
keyword allows you to inherit variables from the parent scope inside your function.