1, 'amount' => 115, 'weight' => 50, // 随便写正整数,越大随机到的概率越大,并且会挤占其他选项的概率 ], [ 'id' => 2, 'amount' => 90, 'weight' => 100 ], [ 'id' => 3, 'amount' => 120, 'weight' => 40 ], [ 'id' => 4, 'amount' => 110, 'weight' => 60 ], [ 'id' => 5, 'amount' => 666, 'weight' => 1 // 大奖填1,概率最小 ], [ 'id' => 6, 'amount' => 66, 'weight' => 50, // 亏钱的,也不要给太高权重,否则都不玩了~ ], [ 'id' => 7, 'amount' => 99, 'weight' => 100 ], [ 'id' => 8, 'amount' => 150, 'weight' => 20, ], [ 'id' => 9, 'amount' => 200, 'weight' => 10 ] ]; private static $price = 100; // 抽奖价格 /** * 抽奖 */ public function golottery(Request $request) { $user = $request->user(); $islottery = Lottery::whereBetween('created_at', [Carbon::today()->startOfDay(), Carbon::today()->endOfDay()])->where('user_id', $user->id)->first(); // return $this->success($user); if ($islottery && $user->amount < $this::$price) return $this->error('像果余额不足'); $arr = []; foreach ($this::$list as $item) { for ($i = 0; $i < $item['weight']; $i++) { $arr[] = $item; } } $resObj = $arr[array_rand($arr)]; // 随机选一个 try { DB::beginTransaction(); $cur_price = $islottery ? $this::$price : 0; Lottery::query()->create([ 'user_id' => $user->id, 'amount' => $cur_price, 'reward_amount' => $resObj['amount'] ]); $user->amount += ($resObj['amount'] - $cur_price); // 加奖励,减花费 $user->save(); DB::commit(); } catch (\Exception $e) { DB::rollBack(); Log::error(__METHOD__, $e->getTrace()); } unset($resObj['weight']); return $this->success($resObj); } /** * 获取奖品列表 */ public function get(Request $request) { $user = $request->user()->toArray(); // return $this->success($user); $islottery = Lottery::whereBetween('created_at', [Carbon::today()->startOfDay(), Carbon::today()->endOfDay()])->where('user_id', $user['id'])->first(); array_walk($this::$list, function (&$item) { unset($item['weight']); $item['check'] = false; }); // 隐藏权重选项 return $this->success([ 'price' => $this::$price, 'free' => !$islottery, // 是否免费 'list' => $this::$list ]); } }