九月丶

PHP获取中奖概率简易算法
<?php if(!function_exists('get_rand')){ /* * ...
扫描右侧二维码阅读全文
24
2018/01

PHP获取中奖概率简易算法

<?php
if(!function_exists('get_rand')){
    /*
     * 通过概率获取中奖id
     * @param $proArr array(7) {
                        [1] =&gt; string(2) "12"
                        [2] =&gt; string(2) "12"
                        [4] =&gt; string(2) "45"
                        [5] =&gt; string(2) "22"
                        [6] =&gt; string(2) "66"
                        [7] =&gt; string(2) "77"
                        [8] =&gt; string(2) "22"
                      }
    *@return id int 7
    */
    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;
    }
}

调用方式:

<?php
if(!empty($data['username'])){
    $prize_arr = Db::table('hisi_game_bless')->where('status','=','1')->field('id,terms,info,odds')->select();
    foreach ($prize_arr as $key => $val) {
        $arr[$val['id']] = $val['odds'];
    }

    $rid = get_rand($arr); //根据概率获取奖项id
    //入库
    $insertId = Db::table('hisi_game_bless_actor')->insertGetId(['username'=>$data['username'],'game_bless_id'=>$rid,'ctime'=>time(),'actor_ip'=>get_client_ip()]);
    //关联取数据
    $log = Db::table('hisi_game_bless_actor')->alias('a')->join('hisi_game_bless b','a.game_bless_id = b.id')->where('a.id','=',$insertId)->find();

    return $this->success('成功','', $log);
}else{
    return $this->error('姓名不能为空');
}
最后修改:2018 年 02 月 11 日 11 : 31 AM
如果觉得我的文章对你有用,请随意赞赏

1 条评论

  1. 老黑

发表评论 取消回复