The Real cha0s
Order emerges out of cha0s :)
Syndicate content

PHP/Drupal

Code snippets or just general knowledge about PHP and/or Drupal.

uasort in Drupal, a weighty subject

If you've ever done any UI coding in Drupal with some elements that need to be arranged in a given order, then this snippet is for you!

Drupal provides us the function element_sort, which sorts an array's elements based on their '#weight' elements. This is fine, but unfortunately '#element' is a Drupal idiom, and even within Drupal we find places where we'd rather sort by 'weight' than by '#weight'.

So we have a problem that fits a well-defined pattern, but is too clunky to solve by writing a million functions for each element (what if you want to sort by '#list_order'?)

What do we do? Generate functions at run-time and cache them, of course!

function array_comp_sort_by($element) {
  static $cache = array();
  
  if (array_key_exists($element, $cache)) return $cache[$element];
  
  $element = "'" . $element . "'";
  return $cache[$element] = create_function('$l, $r', '
    $lw = (is_array($l) && isset($l[' . $element . '])) ? $l[' . $element . '] : 0;
    $rw = (is_array($r) && isset($r[' . $element . '])) ? $r[' . $element . '] : 0;
    
    if ($lw == $rw) return 0;
    
    return $lw < $rw ? -1 : 1;
  ');
}

Hope this saves you not only the minute it takes to write a new function every time, but the mental anguish of knowing there's a pattern there, but having to settle and copy-paste the sort function. ^^

An example of this in use:

    /** Sort them by weight. */
    uasort($modifiers, array_comp_sort_by('weight'));