note 39484 added to function.array-multisort

From: Date: Fri, 30 Jan 2004 06:57:55 +0000
Subject: note 39484 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-64405@lists.php.net to get a copy of this message
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 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39484 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39484&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39484&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#64405) next »