February 27, 2007
Sorting arrays by an arbitary key value in PHP
I often (a couple times a month) have to sort an array of arrays by some arbitrary value located in the internal array. For example, I might want to sort the following structure by name.
Array[0] {
Array[0] {
id => 1
name => mike
age => 20
}
Array[1] {
id => 2
name => bob
age: 21
}
}
I want the same structure returned, but the array containing ‘bob’ in it’s name key must appear first in the array. PHP’s sort() function is insuffficient in this case, it sorts by the first key of each internal array (i.e. ‘id’ in this case).
The solution is to use usort(), which allows for a custom compare function to be used.
function cmp($x, $y) {
if ($x[1] == $y[1]) {
return 0;
} //if
return ($x[1] > $y[1]) ? 1 : -1;
//or return strcmp($x[1], $y[1]);
} //cmp
usort($array, 'cmp');
usort() takes the provided function name and uses it as the compare function between two elements. This also allows you to sort by multiple fields, if the first two fields are equal you can drop down to checking another field, and so on.

Comments(3)