I would like to have a unique sort function for several associative arrays.
The best candidate among the various PHP sort functions would be uksort()
, (usort()
would be ideal, but it changes the array keys to become the numerical index(!)).
For instance (using a simpler array)
function sorting_by_length_desc ($a, $b)
{
return strlen($GLOBALS['arr'][$b]) - strlen($GLOBALS['arr'][$a]);
}
$arr = ('chandler' => 'bing', 'monica' => 'lewinsky');
uksort($arr, 'sorting_by_length_desc');
will make $arr
to be
('monica' => 'lewinsky', 'chandler' => 'bing');
without affecting the keys.
So how to use the same sort function for any array, uksort()
being called at various places in the code? For instance for $arr1
, $arr2
, ..., $arrn
?
Is it necessary to use another global var with the array name to be assigned to the array to be sorted (before the sort), and used globally in the sort function?
There must be something else, cleaner, right?