note 39484 deleted from function.array-multisort by aidan
| From: | aidan@php.net | Date: | Sun, 03 Oct 2004 10:22:22 +0000 |
| Subject: | note 39484 deleted from function.array-multisort by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-77785@lists.php.net to get a copy of this message | ||
Note Submitter: sdavey at datalink dot net dot au
----
Here's another example of using array_multisort() to sort a multidimensional array.
For this example, each element in the primary array represents one row in the table. Each row
array uses the key to store the column name, and the value to store the data.
This array shape would occur in nature if you looped through mysql_fetch_array(), but is the inverse
of what array_multisort() requires.
Here's some sample data:
volume | edition
----------+-----------
67 | 2
86 | 1
85 | 6
98 | 2
86 | 6
67 | 7
We want to ORDER BY volume DESC, edition ASC.
Here's the code:
<?
// The multi-dimensional array, as returned by
// looping through mysql_fetch_array(), etc.
$arr[1] = array("volume" => "67", "edition" => "2");
$arr[2] = array("volume" => "86", "edition" => "1");
$arr[3] = array("volume" => "85", "edition" => "6");
$arr[4] = array("volume" => "98", "edition" => "2");
$arr[5] = array("volume" => "86", "edition" => "6");
$arr[6] = array("volume" => "67", "edition" => "7");
// We want to ORDER BY volume DESC, edition ASC.
// We have an array of "rows", but array_multisort()
// requires an array of "columns" instead. Here's how
// to get the arrays of columns.
foreach ($arr as $key => $row) {
$volume[$key] = $row["volume"];
$edition[$key] = $row["edition"];
}
// Sort by volume DESC, then by edition ASC.
// Plug in $arr at the end so it is sorted by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $arr);
// now arr is ordered
?>
The result dataset:
volume (D)| edition (A)
----------+-----------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7