来源: php随机抽奖及抽奖概率程序_php随机抽奖程序_feitianli37的博客-CSDN博客
php抽奖概率方法
$notice = ‘谢谢回顾’;
$prizeList = [
1=>10, //一等奖中奖概率10%
2=>50,//二等奖中奖概率50%
3=>20,//三等奖中奖概率20%
4=>20//四等奖中奖概率20%
]
$prizeName = [
1=>’一等奖’,
2=>’二等奖’,
3=>’三等奖’,
4=>’四等奖’,
];
//奖项的设置和概率可以手动设置化;
$total = array_sum($prizeList);
foreach($prizeList as $key=>$value) {
$randNumber = mt_rand(1,$total);
if($randNumber<=$value){
$notice = $prizeName[$key];
break;
}else{
$total -=$value;
}
}
var_dump($notice);
php抽奖概率程序
抽奖概率思想:
1.给每一个奖项设置要给概率数,如下面所有奖品综合设置为100,iphone5s是5,也就是5%
2.然后通过php生成随机数函数生成一个在总概率之间的随机数
如:抽第一个奖品5s的时候,因为是第一次foreach循环,产生的随机数就是在0-100之内的,判断是否中奖,则是看生成的随机数是否在0-5之内,如果在则抽中,否则就是循环到第二件奖品,笔记本是10,但是这里要注意一点,产生的随机数应该是减去之前的如5s中的5
<?php
$prize_arr = array(
‘0’ => array(‘id’ => 1, ‘title’ => ‘iphone5s’, ‘v’ => 5),
‘1’ => array(‘id’ => 2, ‘title’ => ‘联系笔记本’, ‘v’ => 10),
‘2’ => array(‘id’ => 3, ‘title’ => ‘音箱设备’, ‘v’ => 20),
‘3’ => array(‘id’ => 4, ‘title’ => ’30GU盘’, ‘v’ => 30),
‘4’ => array(‘id’ => 5, ‘title’ => ‘话费50元’, ‘v’ => 10),
‘5’ => array(‘id’ => 6, ‘title’ => ‘iphone6s’, ‘v’ => 15),
‘6’ => array(‘id’ => 7, ‘title’ => ‘谢谢,继续加油哦!~’, ‘v’ => 10),
);
foreach ($prize_arr as $key => $val) {
$arr[$val[‘id’]] = $val[‘v’];
}
$prize_id = getRand($arr); //根据概率获取奖品id
$data[‘msg’] = ($prize_id == 7) ? 0 : 1; //如果为0则没中
$data[‘prize_title’] = $prize_arr[$prize_id – 1][‘title’]; //中奖奖品
echo json_encode($data);
exit; //以json数组返回给前端
function getRand($proArr) { //计算中奖概率
$rs = ”; //z中奖结果
$proSum = array_sum($proArr); //概率数组的总概率精度
//概率数组循环
foreach ($proArr as $key => $proCur) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $proCur) {
$rs = $key;
break;
} else {
$proSum -= $proCur;
}
}
unset($proArr);
return $rs;
}
?>
https://blog.csdn.net/weixin_40462767/article/details/86525748
https://www.cnblogs.com/shiwenhu/p/5650269.html
————————————————
版权声明:本文为CSDN博主「feitianli37」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/han_cui/article/details/114304746