note 107477 added to function.array-multisort

From: Date: Sat, 11 Feb 2012 23:59:27 +0000
Subject: note 107477 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-186071@lists.php.net to get a copy of this message
When I was working on a search engine, that had to order the results in PHP by multiple arguments, I got stuck on the issue of multisort erasing your (numeral) indexes for a while. Sometimes, it is important to keep these indexes intact. In my case, the indexes were IDs and the values were a percentage of how relevant the object was, considering an earlier query. e.g: $searchResult = (23 => 0.3, 102 => 0.5, 11 => 0.5, 340 => 0.5, 10 => 0.9); I wanted to use array_multisort to first sort DESC on the IDs, and then on the values DESC. i.e. I wanted to show the highest values first, but in case of two (or more) objects with the same value, the higher ID would be shown first. e.g: $searchResult = (10 => 0.9, 340 => 0.5, 102 => 0.5, 11 => 0.5, 23 => 0.3); The easiest way to do this, I think, is: <?php // create a 2-deep array with the values and keys of $searchResult $array = array( $searchResult, array_keys($searchResult) ); // use multisort, first on the values, then on the keys. This will erase the indexes in the $searchResult array array_multisort($array[0], SORT_DESC, $array[1], SORT_DESC); // get the ordered keys back in the $searchResult array $searchResult = array_combine($array[1], $array[0]); unset($array); //clear some memory ?> ---- Server IP: 213.249.64.162 Probable Submitter: 212.64.65.167 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/107477 Del: integrated -- https://master.php.net/note/delete/107477/integrated Del: useless -- https://master.php.net/note/delete/107477/useless Del: bad code -- https://master.php.net/note/delete/107477/bad+code Del: spam -- https://master.php.net/note/delete/107477/spam Del: non-english -- https://master.php.net/note/delete/107477/non-english Del: in docs -- https://master.php.net/note/delete/107477/in+docs Del: other reasons-- https://master.php.net/note/delete/107477 Reject -- https://master.php.net/note/reject/107477 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186071) next »