抽奖概率 PHP
程序员文章站
2022-06-11 23:36:32
...
抽奖概率
<?php function get_rand($proArr) { $result = ''; //概率数组的总概率精度 $proSum = array_sum($proArr); //概率数组循环 foreach ($proArr as $key => $proCur) { $randNum = mt_rand(1, $proSum); if ($randNum <= $proCur) { $result = $key; break; } else { $proSum -= $proCur; } } unset ($proArr); return $result; } $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'=>0), '4' => array('id'=>5,'prize'=>'10Q币','v'=>1), '5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>100), ); //code here eg:unset($prize_arr['0']) foreach ($prize_arr as $key => $val) { $arr[$val['id']] = $val['v']; } $rid = 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; echo "<pre>"; print_r($res); // echo json_encode($res);
2. [代码]抽奖概率
<?php function get_rand($proArr) { $result = ''; //概率数组的总概率精度 $proSum = array_sum($proArr); //概率数组循环 foreach ($proArr as $key => $proCur) { $randNum = mt_rand(1, $proSum); if ($randNum <= $proCur) { $result = $key; break; } else { $proSum -= $proCur; } } unset ($proArr); return $result; } $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'=>0), '4' => array('id'=>5,'prize'=>'10Q币','v'=>1), '5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>100), ); //code here eg:unset($prize_arr['0']) foreach ($prize_arr as $key => $val) { $arr[$val['id']] = $val['v']; } $rid = 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; echo "<pre>"; print_r($res); // echo json_encode($res);
以上就是抽奖概率的内容,更多相关内容请关注PHP中文网(www.php.cn)!