Search
Quotes I love
-Harry Truman
uasort in Drupal, a weighty subject
- This discussion is closed: you can't post new comments.
- This discussion is closed: you can't post new comments.
- This discussion is closed: you can't post new comments.
- This discussion is closed: you can't post new comments.
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'));
Update:
So, in case you were wondering, PHP 5.3 makes this a lot easier. If you were sorting by weight, you can do this with a simple lambda function:
uasort($modifiers, function($l, $r) {
return ($l['weight'] < $r['weight']) ? -1 : ($l['weight'] > $r['weight'] ? 1 : 0);
});
Fun stuff!
