Sorting two dimensional array using PHP

Usually when displaying search results it is quite important to sort them according to the relevant field of the records. A search result containing records with just one field can be easily sorted by storing them in an array and using the asort() or arsort() functions in PHP.

"Adam", '2' => "Jessie", '3' => "Harvey");
asort($results);
print_r($results);
?>
// OUTPUT
Array ( [1] => Adam [3] => Harvey [2] => Jessie )

But things get a little complicated while dealing with multidimensional arrays as shown below


array('name' => "Adam", 'age' => "32"),
'2' => array('name' => "Jessie", 'age' => "19"),
'3' => array('name' => "John", 'age' => "24"),
);
?>

In this case we are not only storing the names but also the age of the users. This compels us to use a multidimensional array which could hold the name and age data together. There is a simple solution to this issue.

Let me demonstrate this in an example. In the above case we intend to sort the users according to their age (and not their name). So the array key we need to consider while sorting is “age”. Now…

Step 1: We need to store all the elements of the sub-array into a temporary array for the purpose of sorting.
Step 2: We then sort this temp array using our conventional method of asort();
Step 3: We will take advantage of the tendency of this function, of not disturbing the key values. Precisely we will get the array with its keys rearranged. In this case “2, 3, 1”.
Step 4: Now we store the record of the user under key=2 in the 1st place, 3 in the 2nd and so on until the last.
Step 5: Recline in the chair and give a smile to the sorted array 😉

Here is the function for this method…

function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
print_r($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}

$results = subval_sort($results,"age");
print_r($results);

//OUTPUT
Array ( [0] => Array ( [name] => Jessie [age] => 19 ) [1] => Array ( [name] => John [age] => 24 ) [2] => Array ( [name] => Adam [age] => 32 ) )

I was desperately looking for such a method and found it on FirstTube.com but it lacked the explanation.

Hope you find it useful! 🙂