A-A+
PHP大转盘中奖概率算法
近日工作中有一项目,APP客户端有大转盘抽奖,具体如何抽奖当然在我们服务端实现洛。下面和大家简单分享一下实现代码:
header("Content-type: text/html; charset=utf-8"); $prize_arr = array( '0' => array('id'=>1,'prize'=>'平板电脑','v'=>1), '1' => array('id'=>2,'prize'=>'数码相机','v'=>5), '2' => array('id'=>3,'prize'=>'音箱设备','v'=>10), '3' => array('id'=>4,'prize'=>'4G优盘','v'=>12), '4' => array('id'=>5,'prize'=>'10Q币','v'=>22), '5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>50), ); $actor = 100; foreach ($prize_arr as $v) { $arr[$v['id']] = $v['v']; } foreach ($arr as &$v) { $v = $v*$actor; } asort($arr); $sum = array_sum($arr); //总概率 $rand = mt_rand(1,$sum); $result = ''; //中奖产品id foreach ($arr as $k => $x) { if($rand <= $x) { $result = $k; break; } else { $rand -= $x; } } $res['yes'] = $prize_arr[$result-1]['prize']; //中奖项 print_r($res);