How to sort multi-dimensional arrays using PHP? Sorting one dimensional array is pretty easy, but to do this with two or multi-dimensional arrays, is a little different. Here is how to do it:
There’s a given 2 dimensional array:
$array[] = array(“id”=>1,”title”=>”Monkey”);
$array[] = array(“id”=>2,”title”=>”Alien”);
$array[] = array(“id”=>3,”title”=>”Stargate”);
$array[] = array(“id”=>4,”title”=>”New”);
We use the usort function of PHP:
usort($array, “cmp”);
… where cmp is the following function:
function cmp($a, $b){
return strcmp($a["title"], $b["title"]);
}
After sorting the $a array, it will look like this:
$array[0] = array(“id”=>2,”title”=>”Alien”);
$array[1] = array(“id”=>1,”title”=>”Monkey”);
$array[2] = array(“id”=>4,”title”=>”New”);
$array[3] = array(“id”=>3,”title”=>”Stargate”);
Now, the array is sorted by ‘title’ in ascending order. To sort in in descending order, just change the order of the compared elements in the cmp function:
return strcmp($b["title"], $a["title"]);
















