🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
```php /** * 计算中奖概率 */ public 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; } ``` ```php /** * 执行抽奖 */ public function get_gift() { $userinfo = $this->auth->getUserinfo(); if ($userinfo['ctimes'] < 1) { $this->error('抽奖次数不够'); } // if (Cache::has('gift202104191626')) { // $prize_arr = Cache::get('gift202104191626'); // } else { $prize_arr = array(); $data = Prize::where([])->order('weigh asc')->select(); foreach ($data as $k => $v) { $ls['id'] = $v['id']; $ls['weigh'] = $v['weigh']; $ls['prize'] = $v['title']; $ls['v'] = $v['probability']; array_push($prize_arr, $ls); } // Cache::set('gift202104191626', $prize_arr); // } //拼装奖项数组 // 奖项id,奖品,概率 // $prize_arr = array( // '0' => array('id' => 1, 'prize' => '平板电脑', 'v' => 1), // '1' => array('id' => 2, 'prize' => '数码相机', 'v' => 2), // '2' => array('id' => 3, 'prize' => '音箱设备', 'v' => 3), // '3' => array('id' => 4, 'prize' => '4G优盘', 'v' => 10), // '4' => array('id' => 5, 'prize' => '10Q币', 'v' => 5), // '5' => array('id' => 6, 'prize' => '空奖', 'v' => 100), // ); // $this->success('', $prize_arr); foreach ($prize_arr as $key => $val) { $arr[$val['weigh']] = $val['v'];//概率数组 } // $this->success('', $arr); $rid = self::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); // $result['id'] = $rid; $result['id'] = bcsub($rid, 1); // $result['subscriptid'] = bcsub($rid, 1); if ($res['yes'] != '谢谢惠顾') { $result['status'] = 1; $result['name'] = $res['yes']; $prize = new Lucky(); $info = Prize::where(['weigh' => $rid])->find(); $prize->data([ 'code' => Random::build('numeric', 9), 'user_id' => $this->auth->id, 'prize_id' => $info['id'] // 'prize_id' => $prize_arr[bcsub($rid, 1)]['id'] ]); $prize->save(); } else { $result['status'] = -1; $result['msg'] = $res['yes']; } \app\admin\model\User::where('id', $this->auth->id)->setDec('ctimes'); $this->success('', $result); } ```