note 103703 added to function.asort

From: Date: Thu, 28 Apr 2011 23:40:22 +0000
Subject: note 103703 added to function.asort
Groups: php.notes 
Request: Send a blank email to php-notes+get-179253@lists.php.net to get a copy of this message
On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com): What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order: Ex: <?php $kvpairs = array('noun' => 'thought', 'animal' => 'fish', 'abstract' => 'thought', 'food' => 'fish', 'verb' => 'fish'); print "before:\n"; print_r($kvpairs); // Essentially, one line of code is all that's needed for the sort: array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs); print "after:\n"; print_r($kvpairs); ?> before: Array ( [noun] => thought [animal] => fish [abstract] => thought [food] => fish [verb] => fish ) after: Array ( [animal] => fish [food] => fish [verb] => fish [abstract] => thought [noun] => thought ) Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it. ---- Server IP: 69.147.83.197 Probable Submitter: 174.25.173.95 ---- Manual Page -- http://www.php.net/manual/en/function.asort.php Edit -- https://master.php.net/note/edit/103703 Del: integrated -- https://master.php.net/note/delete/103703/integrated Del: useless -- https://master.php.net/note/delete/103703/useless Del: bad code -- https://master.php.net/note/delete/103703/bad+code Del: spam -- https://master.php.net/note/delete/103703/spam Del: non-english -- https://master.php.net/note/delete/103703/non-english Del: in docs -- https://master.php.net/note/delete/103703/in+docs Del: other reasons-- https://master.php.net/note/delete/103703 Reject -- https://master.php.net/note/reject/103703 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#179253) next »