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) == “ASC”) ? ’$a,$b’ : ’$b,$a’;</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 /> “First Element” => 1,<br /> “Second Element” => 2,<br /> “Third Element” => 3<br /> );</p> <p>$arr<sup><a href="#fn30073865448b703396849a">1</a></sup> = array(<br /> “First Element” => 4,<br /> “Second Element” => 5,<br /> “Third Element” => 6<br /> );</p> <p>$arr<sup><a href="#fn141413428048b703396d66f">2</a></sup> = array(<br /> “First Element” => 7,<br /> “Second Element” => 8,<br /> “Third Element” => 9<br /> );<br />
With this we can easily sort by the array key name:
orderBy($arr, ‘Second Element’, ‘DESC’);
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.













