i wish i had seen that while writing this (and i was quite awakw.. well, at least i thought so)
i corrected it and implemented functionality to sort using an index not in the 2nd dimension
function sort_array(&$array, $cols, $dir = SORT_ASC, $natsort = true, $keep_keys = false) {
//check whether sorting is really neccessary
if (!is_array($array) or count($array) < 2)
return;
$col = array();
//$cols has to be an array
if (!is_array($cols))
$cols = array($cols);
//check whether sorting is possible
$check = $array[current(array_keys($check))];
foreach ($cols as $col_sort) {
if (!isset($check[$col_sort]))
return;
$col[] = is_numeric($col_sort) ? $col_sort : "'".$col_sort."'";
$check = $check[$col_sort];
}
//keep array indices or not?
$sort = $keep_keys ? 'uasort' : 'usort';
//do natural sort?
$natsort = $natsort ? 'strnatcmp' : 'strcmp';
//check sort order
if ($dir == SORT_DESC)
$natsort = '-1 * '.$natsort;
//convert sort columns
$col = implode('][', $col);
//do sorting
$sort($array, create_function(
'$a, $b',
'return '.$natsort.'($a['.$col.'], $b['.$col.']);')
);
}
$a = array(
array('id' => 5, 'name' => 'pic 3', 'user' => array('nick' => '1st nick', 'mail' => 'a@b.com')),
array('id' => 7, 'name' => 'pic 43', 'user' => array('nick' => '4th nick', 'mail' => 'xy@b.com')),
array('id' => 3, 'name' => 'pic 12', 'user' => array('nick' => '2nd nick', 'mail' => 'a@x.com')),
array('id' => 4, 'name' => 'pic 17', 'user' => array('nick' => '3rd nick', 'mail' => 'mail@example.com')),
array('id' => 11, 'name' => 'pic 2', 'user' => array('nick' => '5th nick', 'mail' => 'a@b.com')),
);
echo '<pre>'.print_r($a, true).'</pre>';
sort_array($a, array('user', 'mail'), SORT_DESC);
echo '<pre>'.print_r($a, true).'</pre>';