note 86558 added to function.array-multisort

From: Date: Thu, 23 Oct 2008 18:47:06 +0000
Subject: note 86558 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-145664@lists.php.net to get a copy of this message
I looked on some forms for an answer to this simple problem and couldn't find one so I came up with a solution that may help in some situations. How do you sort an array by a field in that array and resolve numeric ties randomly? Code: <?php foreach($list as $temp_list) { $sort_aux[] = ($temp_list['column_to_sort_by']+(rand(1, 9)/10)); } array_multisort($sort_aux, SORT_NUMERIC, $list); ?> Example: $list[]=array('name'=>'Tom', 'score'=>3); $list[]=array('name'=>'Sam', 'score'=>3); $list[]=array('name'=>'Joey', 'score'=>1); Explanation: I took an existing example found above that shows how to sort an array by one of it's columns/fields. I just added: "+(rand(1,9)/10)" To randomly add .1 through .9 to their score to resolve the tie. (Obviously this specific example only works if you're sorting by an integer... so you may need to modify it to suit your needs.) Hope this helps someone. ---- Server IP: 69.147.83.197 Probable Submitter: 71.224.220.3 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/86558 Del: integrated -- https://master.php.net/note/delete/86558/integrated Del: useless -- https://master.php.net/note/delete/86558/useless Del: bad code -- https://master.php.net/note/delete/86558/bad+code Del: spam -- https://master.php.net/note/delete/86558/spam Del: non-english -- https://master.php.net/note/delete/86558/non-english Del: in docs -- https://master.php.net/note/delete/86558/in+docs Del: other reasons-- https://master.php.net/note/delete/86558 Reject -- https://master.php.net/note/reject/86558 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#145664) next »