想象一下,我们有一个像下面的样本数组一样的数组,我们希望从中得到随机奖。
但是,我们希望获得每个奖项的胜利控制机会,这意味着我们希望控制哪一个奖品获胜的机会更高或更低。
<?php
$prizes = [
["title" => "1st Prize", "chance" => "10"],
["title" => "2nd Prize", "chance" => "15"],
["title" => "3rd Prize", "chance" => "50"],
["title" => "4th Prize", "chance" => "35"],
["title" => "5th Prize", "chance" => "75"],
["title" => "6th Prize", "chance" => "35"],
["title" => "7th Prize", "chance" => "55"],
["title" => "8th Prize", "chance" => "99"],
["title" => "9th Prize", "chance" => "11"],
];
?>
答案 0 :(得分:1)
首先,这些机会加起来超过100%。是否有可能一次赢得多个奖项?
我这样做的方法就是选择1到100之间的随机数,例如
$rng = rand(1,100);
。
然后将结果与数组的所有chance
字段进行比较。如果随机数等于或小于特定奖品的chance
,则该用户赢得该奖品。
答案 1 :(得分:0)
其中一个做法是总结所有机会,然后随机化一个大数字的数字,看看它在哪里&#34;点击&#34;:
// Sum the chances
$totalChances = 0;
foreach ($prizes as $prize) {
$totalChances += $prize['chance'];
}
// Randomize a number:
$rand = rand(0, $totalChances);
// Pick a prize
$currPize = '';
$currChance = 0;
$i = 0;
do {
$currChance += $prizes[i]['chance'];
$i++;
} while ($currChance < $prizes[i]['chance']);