Sorting a Multi-Dimensional Array with PHP

Every so often I find myself with a multidimensional array that I want to sort by a value in a sub-array. I have an array that might look like this:

//an array of some songs I like
$songs = array(
‘1’ => array(‘artist’=>’The Smashing Pumpkins’, ‘songname’=>’Soma’),
‘2’ => array(‘artist’=>’The Decemberists’, ‘songname’=>’The Island’),
‘3’ => array(‘artist’=>’Fleetwood Mac’, ‘songname’ =>’Second-hand News’)
);

The problem is thus: I’d like to echo out the songs I like in the format “Songname (Artist),” and I’d like to do it alphabetically by artist. PHP provides many functions for sorting arrays, but none will work here. ksort() will allow me to sort by key, but the keys in the $songs array are irrelevant. asort() allows me to sort and preserves keys, but it will sort $songs by the value of each element, which is also useless, since the value of each is “array()”. usort() is another possible candidate and can do multi-dimensional sorting, but it involves building a callback function and is often pretty long-winded. Even the examples in the PHP docs references specific keys.

So I developed a quick function to sort by the value of a key in a sub-array. Please note this version does a case-insensitive sort. See subval_sort() below.

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;
}

To use it on the above, I would simply type:

$songs = subval_sort($songs,’artist’);
print_r($songs);

This is what you should expect see:

Array
(
[0] => Array
(
[artist] => Fleetwood Mac
[song] => Second-hand News
)[1] => Array
(
[artist] => The Decemberists
[song] => The Island
)[2] => Array
(
[artist] => The Smashing Pumpkins
[song] => Cherub Rock
)

)