additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this:
<?
$array['test0'] = array('main' => 'a', 'sub' => 'a');
$array['test2'] = array('main' => 'a', 'sub' => 'b');
$array['test3'] = array('main' => 'b', 'sub' => 'c');
$array['test1'] = array('main' => 'a', 'sub' => 'c');
$array['test4'] = array('main' => 'b', 'sub' => 'a');
$array['test5'] = array('main' => 'b', 'sub' => 'b');
?>
or
<?
$array[0] = array('main' => 1, 'sub' => 1);
$array[2] = array('main' => 1, 'sub' => 2);
$array[3] = array('main' => 2, 'sub' => 3);
$array[1] = array('main' => 1, 'sub' => 3);
$array[4] = array('main' => 2, 'sub' => 1);
$array[5] = array('main' => 2, 'sub' => 2);
?>
on one or more columns.
the code
<? $array = array_natsort_list($array,'main','sub'); ?>
will result in $array being sortet like this:
test0,test2,test1,test4,test5,test3
or
0,2,1,4,5,3.
you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached.
to me it was very usefull for sorting a menu having submenus and even sub-submenus.
i hope it might help you too.
here is the function:
<?
function array_natsort_list($array) {
// for all arguments without the first starting at end of list
for ($i=func_num_args();$i>1;$i--) {
// get column to sort by
$sort_by = func_get_arg($i-1);
// clear arrays
$new_array = array();
$temporary_array = array();
// walk through original array
foreach($array as $original_key => $original_value) {
// and save only values
$temporary_array[] = $original_value[$sort_by];
}
// sort array on values
natsort($temporary_array);
// delete double values
$temporary_array = array_unique($temporary_array);
// walk through temporary array
foreach($temporary_array as $temporary_value) {
// walk through original array
foreach($array as $original_key => $original_value) {
// and search for entries having the right value
if($temporary_value == $original_value[$sort_by]) {
// save in new array
$new_array[$original_key] = $original_value;
}
}
}
// update original array
$array = $new_array;
}
return $array;
}
?>