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.