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']);";
 
	//Figure out which way to sort the comparision function parameters
	$whichWay = (strtoupper($direction) == "ASC") ? '$a,$b' : '$b,$a';
 
	//Recursively call the anonymous function
  	usort($data, create_function($whichWay, $code));
}
 

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

 
$arr = array();
 
$arr[0] = array(
		"First Element"  => 1,
		"Second Element" => 2,
		"Third Element"  => 3
	);
 
$arr[1] = array(
		"First Element"  => 4,
		"Second Element" => 5,
		"Third Element"  => 6
	);
 
$arr[2] = array(
		"First Element"  => 7,
		"Second Element" => 8,
		"Third Element"  => 9
	);
 

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

 
orderBy($arr, 'Second Element', 'DESC');
 

Output:

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

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

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments