Sorting a Multidimensional Array The Easy Way.

Posted by Matt on October 16, 2007

Here is a quick and easy function written in PHP that will allow you to sort a multidimensional array.

 
function orderBy(&$data, $field, $direction){
//Provide the anonymous recursive functionality
  $code = “return strnatcmp(\$a[’$field’], \$b[’$field’]);”;
	<p>//Figure out which way to sort the comparision function parameters<br />
$whichWay = (strtoupper($direction) == &#8220;ASC&#8221;) ? &#8217;$a,$b&#8217; : &#8217;$b,$a&#8217;;</p>
	<p>//Recursively call the anonymous function
  usort($data, create_function($whichWay, $code));<br />
}<br />
 

This function assumes that your array looks something like the following:

 
$arr = array();
	<p>$arr<sup><a href="#fn111647194948b7033964e62">0</a></sup> = array(<br />
&#8220;First Element&#8221;  => 1,<br />
&#8220;Second Element&#8221; => 2,<br />
&#8220;Third Element&#8221;  => 3<br />
);</p>
	<p>$arr<sup><a href="#fn30073865448b703396849a">1</a></sup> = array(<br />
&#8220;First Element&#8221;  => 4,<br />
&#8220;Second Element&#8221; => 5,<br />
&#8220;Third Element&#8221;  => 6<br />
);</p>
	<p>$arr<sup><a href="#fn141413428048b703396d66f">2</a></sup> = array(<br />
&#8220;First Element&#8221;  => 7,<br />
&#8220;Second Element&#8221; => 8,<br />
&#8220;Third Element&#8221;  => 9<br />
);<br />
 

With this we can easily sort by the array key name:

 
orderBy($arr, &#8216;Second Element&#8217;, &#8216;DESC&#8217;);
 

Output:

<br />
Array<br />
(
    [0] => Array
        (
            [First Element] => 7
            [Second Element] => 8
            [Third Element] => 9
        )</p>
    [1] => Array
        (
            [First Element] => 4
            [Second Element] => 5
            [Third Element] => 6
        )
    [2] => Array
        (
            [First Element] => 1
            [Second Element] => 2
            [Third Element] => 3
        )
	<p>)<br />
 

As you can see, the $arr array has been sorted by the ‘Second Element’ key in descending order. Quick and easy.