I'm using a function called subval_sort
to sort a multi-dimensional array.
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
$songs = array(
'1' => array('artist'=>'Bing Crosby', 'songname'=>'White Christmas'),
'2' => array('artist'=>'Elvis Presley', 'songname'=>'White Christmas'),
'3' => array('artist'=>'Abba', 'songname' =>'Waterloo')
);
$songs = subval_sort($songs,'songname');
print_r($songs);
Works fine. Now I want to sort by songname as first and artist as second. So: if two (or more) songname-values are the same I want to sort by artist. Like in SQL: ORDER BY songname, artist.
Do you have any ideas how to solve it?
You can use usort where you can define the custom comparison function
function cmp($a, $b)
{
if(strcmp($a['songname'], $b['songname'])) {
return strcmp($a['songname'], $b['songname']);
}
return strcmp($a["artist"], $b["artist"]);
}
implementation: usort($songs, "cmp");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments