我有这个:
$numbers = range(1,52);
shuffle($numbers);
foreach($users as $user) {
$uniqueRand = array_pop($numbers);
}
这为我的数据库中的每个用户提供了一个唯一的随机数。
我总共有15个用户,是否有可能从1-32填充剩下的范围并重复随机所以说。
现在看起来像这样:
1 - 24
2 - 26
3 - 2
4 - 6
5 - 8
6 - 31
7 - 25
8 - 16
9 - 13
10 - 21
11 - 19
12 - 29
13 - 8
14 - 4
15 - 6
只是具有随机数的用户,是否有可能在给定范围内的所有数字之前,再次随机地将那些未分配给该范围内的用户的数字给予用户?
答案 0 :(得分:0)
<?php
function f($userIds, $numbers)
{
shuffle($numbers); // added
$picks = array();
foreach ($userIds as $id) {
$picks[] = array('id' => $id, 'numbers' => array());
}
// Shuffle order of userIds. Give one number to each user. Repeat both steps
// until all numbers are gone
$n = count($userIds);
$i = 0;
while (!empty($numbers)) {
if ($i % $n === 0) {
shuffle($picks);
}
$picks[$i % $n]['numbers'][] = array_pop($numbers);
$i++;
}
return $picks;
}
$picks = f(array(1, 2, 3, 4, 9, 12, 47, 50), range(1, 30));
foreach ($picks as $p) {
printf("id %s: %s\n", $p['id'], implode(', ', $p['numbers']));
}
将输出如下内容:
id 47: 28, 22, 8, 6
id 1: 30, 17, 12, 5
id 12: 24, 16, 7, 4
id 9: 23, 19, 13, 3
id 50: 25, 18, 14, 2
id 3: 27, 15, 9, 1
id 4: 29, 20, 10
id 2: 26, 21, 11
编辑:忘记了什么。您可能也希望对数字进行洗牌,以获得更随机的分布。在函数中添加了这一行。