编程语言
首页 > 编程语言> > php抽奖概率

php抽奖概率

作者:互联网

测试数据:

 

 

测试表结构:

CREATE TABLE `pt_fenxiao_prize` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `prize` varchar(60) NOT NULL DEFAULT '' COMMENT '奖项名称',
  `rate` int(10) NOT NULL DEFAULT '0' COMMENT '中奖概率',
  `num` int(10) NOT NULL DEFAULT '0' COMMENT '中奖数量',
  `prize_num` int(10) NOT NULL DEFAULT '0' COMMENT '已抽中数量',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 

抽奖demo

<?php
/**
 * Created by PhpStorm.
 * User: HOUDJ
 * Date: 2021/1/29
 * Time: 13:44
 */

namespace app\api\controller;


use think\Db;

class Prize extends Base
{
    /**
     * Notes:抽奖
     * User: HOUDJ
     * Date: 2021/1/29
     * Time: 14:52
     */
    public function prize(){
        $list=Db::name('fenxiao_prize')->select();
        $key=$this->prizeHandle($list);
        if($key){
            Db::name('fenxiao_prize')->where('id',$key)->setInc('prize_num');
            $prizename=Db::name('fenxiao_prize')->where('id',$key)->value('prize');
            echo '恭喜您,喜中'.$prizename;
        }else{
            echo '哎呀 没中奖';
        }
    }

    /**
     * Notes:抽奖操作
     * User: HOUDJ
     * Date: 2021/1/29
     * Time: 14:49
     * @param $prizes
     * @return int|string
     */
    public function prizeHandle($prizes){
        //进行抽奖
        $data = [];
        foreach ($prizes as $prize) {
            if (($prize['num'] - $prize['prize_num']) > 0) {
                $data[$prize['id']] = $prize['rate'];
            }
        };

        //获取所有奖品的总概率
        $sum = array_sum($data);
        $countSum = 100;
        if ($sum < $countSum) {
            $data[0] = $countSum - $sum;//不满100%,表示没有抽取到奖品
        }
        $result = 0;
        //概率数组总精度
        //概率数组循环
        foreach ($data as $key => $value) {
            $randNum = mt_rand(1, $countSum);
            if ($randNum <= $value) {
                $result = $key;
                break;
            } else {
                $countSum -= $value;
            }
        }
        unset($data);
        return $result;//抽到的ID值,0表示没有抽到奖品
    }
}

 

标签:概率,num,prize,DEFAULT,NULL,int,抽奖,key,php
来源: https://www.cnblogs.com/houdj/p/14344965.html