views:

35

answers:

1

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?

+1  A: 

You can have a common comparison function like:

function sorting_by_length_desc ($a, $b) {
        return strlen($b) - strlen($a);
}

Also uksort sorts the array on keys. Is that what you are looking for?

If you want to sort the arrays on value maintaining the key,value association you can use uasort.

codaddict
I completely missed this func for some reason! `uasort()` is exactly what is needed to achieve the problem I had in the first place. Thanks.
ring0