Fork me on GitHub

article

Sort arrays by key revisited

July 29, 2009 | PHP Scripting

I don’t know why but I have an infatuation with little utility functions. Its pretty stupid, but it keeps me entertained and provides me with a cheap blog post ๐Ÿ˜‰ That and I’ve noticed it trending A LOT in my search keywords lately, so I figure I should post some updated and easier to use code.

A few years ago I posted on Sorting Multidimensional Arrays by Key. The solution had php4 and php5 version and they were class based. Kind of awkward to use. They were originally dumped in a framework and accessed statically. After much tweaking and moving it from project to project it is down to a single function that also sorts arrays of objects my member variables.

  1.  <?php
  2.  /**
  3.   * Sort an array by a key within the array_items
  4.   * Items can be arrays or objects, but must all be the same type
  5.   *
  6.   * @example
  7.   * $array = array(
  8.   * 'mary' => array('age' => 21),
  9.   * 'bob' => array('age' => 5),
  10.   * 'justin' => array('age' => 15)
  11.   * );
  12.   * $array = cf_sort_by_key($array,'age');
  13.   * # array is now: bob,justin,mary
  14.   *
  15.   * @param $data - the array of items to work on
  16.   * @param $sort_key - an array key or object member to use as the sort key
  17.   * @param $ascending - wether to sort in reverse/descending order
  18.   * @return array - sorted array
  19.   */
  20.  function array_sort_by_key($data,$sort_key,$ascending=true) {
  21.   $order = $ascending ? '$a,$b' : '$b,$a';
  22.   ย 
  23.   if(is_object(current($data))) {
  24.   $callback = create_function($order,'return strnatcasecmp($a->'.$sort_key.',$b->'.$sort_key.');');
  25.   } else {
  26.   $callback = create_function($order,'return strnatcasecmp($a["'.$sort_key.'"],$b["'.$sort_key.'"]);');
  27.   }
  28.   ย 
  29.   uasort($data,$callback);
  30.   return $data;
  31.  }

Less code. Easier to use. Single code base for php4 and php5. And once php 5.3 becomes more ubiquitous I can rewrite it again to use lambda functions ๐Ÿ˜‰