PHP中奖概率的抽奖算法程序代码
1.可以控制中奖的概率,2.具有随机性,3.最好可以控制奖品的数量,4.根据用户ID或者ip、手机号、QQ号等条件限制抽奖次数
初期就这些需求,然后根据网上的资料,采用了一种阶段式抽取的方法,大家下面看一下整体的程序.该程序是在ThinkPHP框架下完成的,使用了一些框架自带的类库和函数,下面我会逐一进行说明,控制器部分,代码如下:
- <?php
-
-
-
-
-
- class ChoujiangAction extends Action {
-
-
- var $begin_time="2012-12-25 14:00:00";
-
- var $stop_time="0";
-
-
-
- var $prize_arr = array(
- '0' => array('id' => 1, 'prize' => '44元购买1G/年空间', 'v' => 1,'num'=>1),
- '1' => array('id' => 2, 'prize' => '55元购买1G/年空间', 'v' => 2,'num'=>2),
- '2' => array('id' => 3, 'prize' => '66元购买1G/年空间', 'v' => 5,'num'=>2),
- '3' => array('id' => 4, 'prize' => '77元购买1G/年空间', 'v' => 10,'num'=>3),
- '4' => array('id' => 5, 'prize' => '88元购买1G/年空间', 'v' => 15,'num'=>4),
- '5' => array('id' => 6, 'prize' => '99元购买1G/年空间', 'v' => 67,'num'=>10),
- );
-
-
-
- public function index(){
-
- $Choujiang=M('Choujiang');
- $this->assign('list', $Choujiang->where("rid>0")->order('id desc')->select());
- unset($Choujiang);
-
-
- $this->assign('begin_time',$this->begin_time);
-
- $this->display();
- }
-
-
-
-
-
-
- public function make() {
- $qq_no= trim($_POST['qq_no']);
- import('ORG.Util.Input');
- $qq_no=Input::getVar($qq_no);
-
- if(emptyempty($qq_no)){
- $this->ajaxReturn(1, '请正确填写QQ号码!');
- exit;
- }
-
- if(!emptyempty($this->begin_time) && time()<strtotime($this->begin_time)){
- $this->ajaxReturn(1, '抽奖还没有开始,开始时间为:'.$this->begin_time);
- exit;
- }
-
- if(!emptyempty($this->stop_time) && time()>strtotime($this->stop_time)){
- $this->ajaxReturn(1, '本次抽奖已经结束,结束时间为:'.$this->stop_time);
- exit;
- }
-
-
- $prize_arr= $this->prize_arr;
-
- foreach ($prize_arr as $key => $val) {
- $arr[$val['id']] = $val['v'];
- }
-
- $rid = $this->get_rand($arr);
-
- $str = $prize_arr[$rid - 1]['prize'];
-
- $Choujiang=M('Choujiang');
-
-
- if($Choujiang->where("qq_no='{$qq_no}'")->count()>=3){
- $str='您3次抽奖机会已经用完!';
- $rid=0;
-
- }elseif ($Choujiang->where("rid={$rid}")->count()>=$prize_arr[$rid-1]['num']) {
- $str='很抱歉,您所抽中的奖项已经中完!';
- $rid=0;
- }
-
- $data=array(
- 'rid'=>$rid,
- 'pop'=>$str,
- 'qq_no'=>$qq_no,
- 'input_time'=>time()
- );
-
-
- $Choujiang->add($data);
- unset($Choujiang);
-
-
- $this->ajaxReturn(1, $str);
- }
-
-
-
-
- private 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;
- }
-
- }
- ?>
该算法简单使用,并发访问性能非常好,稍加改动就可以用于各种场合,结合用户登录等信息可有效控制每个人的抽奖次数,将开始和结束之间更改为数组,就可以完善成为每天特定时间抽奖的程序.