PHP实现转盘抽奖算法分享
本文实例为大家分享了PHP实现转盘抽奖算法的具体代码,供大家参考,具体内容如下
流程:
1.拼装奖项数组
2.计算概率
3.返回中奖情况
代码如下:
中奖概率 ' v ' 可以在后台设置,传到此方法中,注意传整数
function get_gift(){ //拼装奖项数组 // 奖项id,奖品,概率 $prize_arr = array( '0' => array('id'=>1,'prize'=>'平板电脑','v'=>0), '1' => array('id'=>2,'prize'=>'数码相机','v'=>0), '2' => array('id'=>3,'prize'=>'音箱设备','v'=>0), '3' => array('id'=>4,'prize'=>'4G优盘','v'=>5), '4' => array('id'=>5,'prize'=>'10Q币','v'=>0), '5' => array('id'=>6,'prize'=>'空奖','v'=>5), ); foreach ($prize_arr as $key => $val) { $arr[$val['id']] = $val['v'];//概率数组 } $rid = $this->get_rand($arr); //根据概率获取奖项id $res['yes'] = $prize_arr[$rid-1]['prize']; //中奖项 unset($prize_arr[$rid-1]); //将中奖项从数组中剔除,剩下未中奖项 shuffle($prize_arr); //打乱数组顺序 for($i=0;$i<count($prize_arr);$i++){ $pr[] = $prize_arr[$i]['prize']; //未中奖项数组 } $res['no'] = $pr; // var_dump($res); if($res['yes']!='空奖'){ $result['status']=1; $result['name']=$res['yes']; }else{ $result['status']=-1; $result['msg']=$res['yes']; } //return $result; var_dump($result); } //计算中奖概率 function get_rand($proArr) { $result = ''; //概率数组的总概率精度 $proSum = array_sum($proArr); // var_dump($proSum); //概率数组循环 foreach ($proArr as $key => $proCur) { $randNum = mt_rand(1, $proSum); //返回随机整数 if ($randNum <= $proCur) { $result = $key; break; } else { $proSum -= $proCur; } } unset ($proArr); return $result; }
效果图:
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23