note 86552 added to function.array-multisort
| From: | matt at idizinc dot com | Date: | Thu, 23 Oct 2008 15:06:33 +0000 |
| Subject: | note 86552 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-145644@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: 99.189.253.87
----
Manual Page -- http://www.php.net/manual/en/function.array-multisort.php
Edit -- https://master.php.net/note/edit/86552
Del: integrated -- https://master.php.net/note/delete/86552/integrated
Del: useless -- https://master.php.net/note/delete/86552/useless
Del: bad code -- https://master.php.net/note/delete/86552/bad+code
Del: spam -- https://master.php.net/note/delete/86552/spam
Del: non-english -- https://master.php.net/note/delete/86552/non-english
Del: in docs -- https://master.php.net/note/delete/86552/in+docs
Del: other reasons-- https://master.php.net/note/delete/86552
Reject -- https://master.php.net/note/reject/86552
Search -- https://master.php.net/manage/user-notes.php