note 69656 added to function.array-multisort

From: Date: Thu, 14 Sep 2006 07:04:24 +0000
Subject: note 69656 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-117145@lists.php.net to get a copy of this message
Often, one may have a group of arrays which have parallel data that need to be kept associated with each other (e.g., the various attribute values of a group of elements might be stored in their own arrays). Using array_multisort as is, by specifying additional fields, it is possible, as in the documentation example cited below, that this association will be lost. To take this example set of data from the documentation: <?php $ar1 = array("10", 100, 100, "a"); $ar2 = array(1, 3, "2", 1); ?> The example goes on to sort it this way: <?php array_multisort($ar1, $ar2); ?> In this case, although the "10" remains associated with the first '1' after being sorted, the "2" and '3' are reversed from their original order. In order to sort by one field only (yet still have the other array(s) being correspondingly sorted), one can use array_keys (which makes an array out of the keys) to ensure that no further sub-sorting is performed. This works because array_keys is making an array for which no duplicates can exist (since keys will be unique), and thus, the subsequent fields will have no relevance as far as subsorting. So, using the above data, we can perform this sort instead: <?php $ar3 = array_keys($ar1); array_multisort($ar1, $ar3, $ar2); ?> which, when $ar1 and $ar2 are dumped gives: array(4) { [0]=> string(2) "10" [1]=> string(1) "a" [2]=> int(100) [3]=> int(100) } array(4) { [0]=> int(1) [1]=> int(1) [2]=> int(3) [3]=> string(1) "2" } ---- Server IP: 219.239.98.8 Probable Submitter: 218.17.96.1 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/69656 Del: integrated -- https://master.php.net/note/delete/69656/integrated Del: useless -- https://master.php.net/note/delete/69656/useless Del: bad code -- https://master.php.net/note/delete/69656/bad+code Del: spam -- https://master.php.net/note/delete/69656/spam Del: non-english -- https://master.php.net/note/delete/69656/non-english Del: in docs -- https://master.php.net/note/delete/69656/in+docs Del: other reasons-- https://master.php.net/note/delete/69656 Reject -- https://master.php.net/note/reject/69656 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#117145) next »