技术饭
ThinkPHP抽奖案例
copylian
0 评论
20456 浏览
2017.01.01
ThinkPHP抽奖案例,之前做过微信的抽奖功能,本来也是不太懂,后来百度了一下,就整理了一下中奖概率算法,现在分享出来给大家用啦!代码相对比较简单,一看就能明白,可以自己拿回去测试一下再放到正式项目中去使用!
ThinkPHP抽奖代码:
<?php /** * [shake 摇一摇] * @param string $value [description] * @return [type] [description] */ public function shake() { if(IS_POST){ //验证是否登录 $tid = $this->tid; $session_name = $this->session_name; //获取session id $uid = session($session_name); $wherestr0 = "id='$uid' and tid='$tid' and isDel = '0'"; $wx = $this->member->where($wherestr0)->find(); if(!$wx){ session($session_name,null); $member_id = $_GET['member_id']; $token = $_GET['token']; R('AuthXmyaoyao/auth',array($member_id,$token,U('index',false,false,true))); $uid = session($session_name); $wherestr0 = "id='$uid' and tid='$tid' and isDel='0'"; $wx = $this->member->where($wherestr0)->find(); } //获取用户信息 $uid = $wx['id']; $uname = $wx['name']; $utel = $wx['mobile']; //获取时间 $timeset = M('XmyaoyaoTimeset')->find(); //验证时间,当前时间大于开始时间小于结束时间 $nowtime = time(); $startime = $timeset['starttime']; $endtime = $timeset['endtime']; if($nowtime >= $endtime){ $this->error('活动已经结束!'); } if($nowtime < $startime){ $this->error('活动还没开始!'); } $XmyaoyaoLog = M('XmyaoyaoLog'); //判断当前用户是否参与过 $one_where['uid'] = array('eq',$uid); //$one_where['uname'] = array('eq',$uname); $one_where['utel'] = array('eq',$utel); $one_where['tid'] = array('eq',$this->tid); $one_log = $XmyaoyaoLog->where($one_where)->find(); if($one_log){ $this->error('您已经参与过了!'); } //奖品数组 $prize_arr = array( 'one' => array('id'=>1,'num'=>3,'prize'=>'一等奖','v'=>10), 'two' => array('id'=>2,'num'=>5,'prize'=>'二等奖','v'=>20), 'three' => array('id'=>3,'num'=>20,'prize'=>'三等奖','v'=>30), 'four' => array('id'=>4,'num'=>0,'prize'=>'未中奖','v'=>40) ); //获取id对应的数组 array(1=>10,2=>15,3=>50,4=>25) foreach ($prize_arr as $key => $val) { $arr[$key] = $val['v']; } $rid = get_rand($arr); //验证商品库存是否还足够,如果不够就提示没有中奖 $check_where['tid'] = array('eq',$this->tid); $check_where['jpid'] = array('eq',$prize_arr[$rid]['id']); $count = $XmyaoyaoLog->where($check_where)->count(); if($count >= $prize_arr[$rid]['num']){ $rid = 'four'; } //写入数据 $add_data['tid'] = $this->tid; $add_data['uid'] = $uid; $add_data['uname'] = $uname; $add_data['utel'] = $utel; $add_data['jpid'] = $prize_arr[$rid]['id']; $add_data['jpname'] = $prize_arr[$rid]['prize']; $add_data['ip'] = get_client_ip(); $add_data['addtime'] = time(); if($XmyaoyaoLog->add($add_data)){ if($rid != 'four'){ $this->success('恭喜您获得'.$prize_arr[$rid]['prize'].''); } else { $this->error('啊哦!用力过猛奖品摇没了……'); } } else { $this->error('数据更新失败!'); } } else { $this->error('非法操作'); } } ?>
中奖概率算法
<?php /* *中奖概率算法 */ function get_rand($proArr) { $result = ''; //概率数组的总概率精度 $proSum = array_sum($proArr); //概率数组循环 asort($proArr,SORT_NUMERIC); foreach ($proArr as $key => $proCur) { $randNum = mt_rand(1, $proSum); if ($randNum <= $proCur) { $result = $key; break; } else { $proSum -= $proCur; } } unset ($proArr); return $result; } ?>
感谢你的支持,我会继续努力!
扫码打赏,感谢您的支持!
文明上网理性发言!