Published 18:25 on 22 September, 2005

Sooner or later, whilst using arrays in PHP, you’re going to want to re-order the data. On a one-dimensional array this simply requires us to run one of the sort(), rsort(), asort() or ksort() commands (depending on what we are doing).

However, should we be using a mult-dimensional array, we need to use the array_multisort() PHP command.

If our array is a database result, it is usually a two-dimensional array arranged in rows but array_multisort() sorts using columns. For this reason we need to do some hefty work preparing our array for ordering. Because of this, I ended up writing this short function the other day:

function do_result_sort($arr_data, $str_column, $bln_desc = false)
  $arr_data                 = (array) $arr_data;
  $str_column               = (string) trim($str_column);
  $bln_desc                 = (bool) $bln_desc;
  $str_sort_type            = ($bln_desc) ? SORT_DESC : SORT_ASC;

  foreach ($arr_data as $key => $row)
    ${$str_column}[$key]    = $row[$str_column];

  array_multisort($$str_column, $str_sort_type, $arr_data);

  return $arr_data;

This function basically allows me to reorganise a result set array by any column either DESC or ASC (however, only one column at a time - with a little hacking we could change that easily).

Since I’ve found this remarkably useful on occasion, I thought I’d share it with the world…

Update: Just realised that I didn’t give you an example of it in use. Consider that corrected:

< ?php
// Here's an array...
$arr_test = array(array('name' => 'tim', 'veg' => 'carrots'),
                  array('name' => 'rob', 'veg' => 'swede'),
                  array('name' => 'mark', 'veg' => 'brocolli'),
                  array('name' => 'apaul', 'veg' => 'sprouts'),
                  array('name' => 'russell', 'veg' => 'mushrooms'),
                  array('name' => 'stupot', 'veg' => 'leeks'));

// Stick it through our function to sort it...
$arr_test = do_result_sort($arr_test, 'name');