note 86552 rejected from function.array-multisort by danbrown
| From: | danbrown@php.net | Date: | Thu, 23 Oct 2008 15:49:56 +0000 |
| Subject: | note 86552 rejected from function.array-multisort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-145647@lists.php.net to get a copy of this message | ||
Note Submitter: matt at idizinc dot com
----
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.