View Full Version : Sorting an multidimensional array

11-06-2005, 04:40 PM
This function sorts a multidimensional (tabular) array by one or more columns.

/* usage
sortDataSet(data set, column1[, mixed arg [, mixed ... [, array ...]]])
/* arguments
the first argument is the multidimensional array
subsequent arguments follow the argument order of array_multisort(),
except that you do not pass arrays to the function but keys (string!) of the columns
/* note
read the documentation of array_multisort() for more information
function sortDataSet(&$dataSet) {
$args = func_get_args();
$callString = 'array_multisort(';
$usedColumns = array();
for($i = 1, $count = count($args); $i < $count; ++$i) {
switch(gettype($args[$i])) {
case 'string':
$callString .= '$dataSet[\''.$args[$i].'\'], ';
array_push($usedColumns, $args[$i]);
case 'integer':
$callString .= $args[$i].', ';
throw new Exception('expected string or integer, given '.gettype($args[$i]));
foreach($dataSet as $column => $array) {
if(in_array($column, $usedColumns)) continue;
$callString .= '$dataSet[\''.$column.'\'], ';
eval(substr($callString, 0, -2).');');

/* example usage */
$latestPost = array(
'title' => array(
'name' => array(
'date' => array(
sortDataSet($latestPost, 'name', SORT_DESC, SORT_STRING, 'title', SORT_DESC, SORT_STRING);
echo '<pre>';
echo '</pre>';

12-12-2005, 06:35 PM
The following shoud do it. pass the array, index is what element you want to sort on (in your case use 3). Then you can sort asc or desc, and weather you want to use natural sorting (the way a human would sort, 2 before 10) and lastly case sensitive or not if using natural sort. Only the first 2 args are needed, the rest will default.

function sort2d ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE)
if(is_array($array) && count($array)>0)
foreach(array_keys($array) as $key)
($order=='asc')? asort($temp) : arsort($temp);
($case_sensitive)? natsort($temp) : natcasesort($temp);
foreach(array_keys($temp) as $key)
(is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
return $sorted;
return $array;

08-04-2011, 01:14 PM
Wow! Thank you for sharing so usefull information

11-23-2011, 04:21 PM
When sorting alphabetically, is there a way to ignore the word "The".
I'm running into this issue with a list of company names.

Corporation B
Test Industries
The Best Way
Tims Company

Ideally, 'The Best Way' would be sorted by 'Best' and not 'The'.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum