Sorting multi-dimensional arrays
When using functions such as my simple PHP database access it is often useful to be able to sort by a field in an array (assuming you cannot use the SQL to define the order for some reason).
As an example, I have a list of 3 cars:
array(
array( 'name' => 'Holden', 'colour' => 'blue' ),
array( 'name' => 'Honda', 'colour' => 'red'),
array( 'name' => 'Ford', 'colour' => 'yellow'),
);
And I want them sorted by name. I've written a simple function that uses this method.
/**
* Sort a multi dim array by a key
*
* Sorts ascending direction only
*
* @return array
* @param $array array
* @param $field string The key to sort by
*/
function sort_by( $array, $field ) {
if( !is_callable("compare_by_$field") ) {
eval(
"function compare_by_$field( \$x, \$y ) {
if (\$x['$field'] == \$y['$field']) { return 0; }
return (\$x['$field'] > \$y['$field']) ? 1 : -1;
}"
);
}
usort( $array, "compare_by_$field" );
return $array;
}
I hope this is useful to people, feel free to use it as you see fit.
1 November 2007