PHP概率,抽奖
随机数,游标卡尺。
一个大饼,随机到哪个坑里,就中哪个奖。
大转盘!
公平公正!
<?php
/**
* 抽取礼物
* $weight_list = [
* [
* 'id' => 1,
* 'name' => '手机',
* 'weight' => 100
* ],
* [
* 'id' => 2,
* 'name' => '电脑',
* 'weight' => 100
* ],
* [
* 'id' => 3,
* 'name' => '洗衣机',
* 'weight' => 100
* ],
* ];
*
*/
function getPrize($weight_list) {
foreach ($weight_list as $gv) {
$giftWeightArr[$gv['id']] = $gv['weight'];
}
$result = '';
//概率数组的总概率精度
$sumWeight = array_sum($giftWeightArr); //计算数组中元素的和
$luckyNum = mt_rand(1, $sumWeight);
//概率数组循环
$beginCursor = $endCursor = 0;
foreach ($giftWeightArr as $id => $weight) {
$beginCursor = $endCursor;
$endCursor += $weight;
if ($luckyNum > $beginCursor && $luckyNum <= $endCursor) {
$result = $id;
break;
}
}
return $result;
}
// 获取锦鲤
function doGet() {
$gift_bag = [
[
'id' => 1,
'name' => '手机',
'weight' => 100
],
[
'id' => 2,
'name' => '电脑',
'weight' => 100
],
[
'id' => 3,
'name' => '洗衣机',
'weight' => 100
]
];
for ($i=0;$i<10;$i++) {
$gid = getPrize($gift_bag); //根据概率获取奖项id
echo $gift_bag[$gid-1]['name'].PHP_EOL;
}
}
doGet();
string(24) "抱歉,下次就中了"
string(24) "抱歉,下次就中了"
string(24) "抱歉,下次就中了"
string(24) "抱歉,下次就中了"
string(24) "抱歉,下次就中了"
string(24) "抱歉,下次就中了"
string(24) "抱歉,下次就中了"
string(9) "小金猪"
string(24) "抱歉,下次就中了"
string(9) "小金猪"
有点意思哦!