PHP - Multidimensional Arrays - Multidimensional Arrays

Multidimensional Arrays


You want to sort a multidimensional array using multiple keys.

Solution Use PHP’s array_multisort() function:
// create a multidimensional array
$data = array();
$data[0] = array("title" => "Net Force", "author" => "Clancy, Tom", ↵
"rating" => 4);
$data[1] = array("title" => "Every Dead Thing", "author" => "Connolly, ↵
John", "rating"=> 5);
$data[2] = array("title" => "Driven To Extremes", "author" => "Allen, ↵
James", "rating" => 4);
$data[3] = array("title" => "Dark Hollow", "author" => "Connolly, ↵
John", "rating" => 4);
$data[4] = array("title" => "Bombay Ice", "author" => "Forbes, ↵
Leslie", "rating" => 5);
// separate all the elements with the same key
// into individual arrays
foreach ($data as $key=>$value) {
$author[$key] = $value['author'];
$title[$key] = $value['title'];
$rating[$key] = $value['rating'];
// sort by rating and then author
array_multisort($rating, $author, $data);

If you’re familiar with Structured Query Language (SQL), you already know how the ORDER BY clause enables you to sort a resultset by more than one field. That’s essentially what the array_multisort() function was designed to do:

it accepts a series of input arrays and uses them as sort criteria. Sorting begins with the first array; values in that array that evaluate as equal are sorted by the next array, and so on.

This function comes in handy when dealing with symmetrical multidimensional arrays, like the one in the previous listing. Such an array is typically created from an SQL resultset. To sort such an array, first break it into individual single arrays, one for each unique key, and then use array_multisort() to sort the arrays in the priority you desire. In such a situation, the last argument to array_multisort() must be the original multidimensional array.