码迷,mamicode.com
首页 > Web开发 > 详细

php随机抽奖实例分析

时间:2015-06-03 19:06:17      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

<?php 
header(‘Content-type:text/html;charset=utf-8‘);
/**

 * 抽奖工具

 */

class lottery_tool {
    protected static $awardsArr;
    protected static $proField = ‘probability‘;
    protected static $proSum = 0;
    protected static $checkAward = false;
    const SUCCESS_CODE = 0;
    const FAIL_CODE = -1;
    //检查抽奖数据
    protected static function checkAwards(){
        if (!is_array(self::$awardsArr) || empty(self::$awardsArr)) {
            return self::$checkAward = false;
        }
        self::$proSum = 0;
        foreach (self::$awardsArr as $_key => $award) {
            self::$proSum += $award[self::$proField];
        }
        if (empty(self::$proSum)) {
            return self::$checkAward = false;
        }
        return self::$checkAward = true;
    }

    protected static function successRoll($rollKey){
        return array(‘code‘ => self::SUCCESS_CODE, ‘roll_key‘ => $rollKey, ‘msg‘ => ‘roll success‘);
    }

    protected static function failRoll($msg = ‘roll fail‘){
        return array(‘code‘ => self::FAIL_CODE, ‘msg‘ => $msg );
    }

    //抽奖

    public static function roll () {
        if (false == self::$checkAward) {
            return self::failRoll(‘awards data is not the right format!‘);
        }

        $result = mt_rand(0, self::$proSum);
        $proValue = 0;
        foreach (self::$awardsArr as $_key => $value) {
            $proValue += $value[self::$proField]; 
            if ($result <= $proValue) {
                return self::successRoll($_key);
            }
        }
        return self::failRoll(‘wrong‘);
    } 

    //改变概率字段名
    public static function setProField($field = null) {
        if (!empty($field)) {
            self::$proField = $field;
        }
    }

    //设置奖品
    public static function setAwards($awards){
        self::$awardsArr = $awards;
        self::checkAwards();
    }
}

$awards = array(
        ‘0‘ => array(‘pro‘ => 1, ‘info‘ => ‘1%的可能性‘ , ‘num‘ =>0),
        ‘1‘ => array(‘pro‘ => 25, ‘info‘ => ‘25%的可能性‘ , ‘num‘ =>0),
        ‘2‘ => array(‘pro‘ => 40, ‘info‘ => ‘40%的可能性‘ , ‘num‘ =>0),
        ‘3‘ => array(‘pro‘ => 34, ‘info‘ => ‘34%的可能性‘ , ‘num‘ =>0),
    );
 //改变概率字段名
lottery_tool::setProField(‘pro‘);
//设置奖品
lottery_tool::setAwards($awards);
$result = array();

for ($i = 100; $i --;) {
     //抽奖
    $result[] = lottery_tool::roll();
}

foreach ($result as $key => $value) {
    $awards[$value[‘roll_key‘]][‘num‘] ++;
}

echo ‘<pre>‘;
var_dump($awards);

 

php随机抽奖实例分析

标签:

原文地址:http://www.cnblogs.com/phpfensi/p/4549649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!