PHP sorting array values
There are many sorting functions available in PHP, but none will sort an array by values. Let me first show you an example:
$array = array();
$array[] = array('id' => 1, 'name' => 'fred', 'sex' => 'male');
$array[] = array('id' => 4, 'name' => 'james', 'sex' => 'male');
$array[] = array('id' => 3, 'name' => 'lisa', 'sex' => 'female');
$array[] = array('id' => 2, 'name' => 'anne', 'sex' => 'female');
Above is a simple multi dimensional array consisting of an id, name and sex of made up people. Let's say we want to sort by name. To do this we would need to use PHP's uasort function. This is a user defined function which gives us more flexibility.
function cmp($a, $b) {
if ($a['name'] == $b['name']) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
}
uasort($array, 'cmp');
print_r($array);
Array
(
[3] => Array
(
[id] => 2
[name] => anne
[sex] => female
)
[0] => Array
(
[id] => 1
[name] => fred
[sex] => male
)
[1] => Array
(
[id] => 4
[name] => james
[sex] => male
)
[2] => Array
(
[id] => 3
[name] => lisa
[sex] => female
)
)
The above function has now sorted our array by the peoples names. This is adequate but there is a slight problem with it. We have hard coded the name key into our function. If we changed our mind and wanted to sort by id, we would have to either write another function or change our existing function to accommodate the id key. One option to fix this dilemma is to use a global variable.
function cmp($a, $b) {
global $sortKey;
if ($a[$sortKey] == $b[$sortKey]) {
return 0;
}
return ($a[$sortKey] < $b[$sortKey]) ? -1 : 1;
}
$sortKey = 'name';
uasort($array, 'cmp');
We have improved our script so it is more versatile but we are using a global variable which can cause other problems. So let's try and move our function into a class and call it wsort.
class wsort
{
function sortByKey($array) {
uasort($array, array('self', 'compare'));
return $array;
}
function compare($a, $b) {
global $sortKey;
if ($a[$sortKey] == $b[$sortKey]) {
return 0;
}
return ($a[$sortKey] < $b[$sortKey]) ? -1 : 1;
}
}
$sortKey = 'name';
$array = wsort::sortByKey($array);
That gives us much more flexibility when sorting arrays in PHP. We now we have an opportunity to get rid of the global variable.
class wsort
{
private static $key;
function sortByKey($array, $key) {
self::$key = $key;
uasort($array, array('self', 'compare'));
return $array;
}
function compare($a, $b) {
if ($a[self::$key] == $b[self::$key]) {
return 0;
}
return ($a[self::$key] < $b[self::$key]) ? -1 : 1;
}
}
$array= wsort::sortByKey($array, 'name');
Now our sort is working without a global variable and is also flexible by the fact that we can send it different keys. We now also have a great opportunity to expand our class and add new methods when required.
Feel free to add this PHP class to your library.