php按照奖品百分比随机抽奖代码分析_PHP教程

WBOY
Release: 2016-07-14 10:11:57
Original
1188 people have browsed it

/**
 * 概率算法
 * @param array $probability
 * @return integer|string
 */
function get_rand($probability) {
    // 概率数组的总概率精度
    $max = array_sum($probability);
    foreach ($probability as $key => $val) {
        $rand_number = mt_rand(1, $max);//从1到max中随机一个值

        if ($rand_number <= $val) {//如果这个值小于等于当前中奖项的概率,我们就认为已经中奖
            return $key;
        } else {
            $max -= $val;//否则max减去当前中奖项的概率,然后继续参与运算
        }
    }
    /**
     * 综上分析:
     *      确保对每个人获取奖品的概率是一样的
     *      如果某件奖品没了,应该讲概率修改为0
     *      考虑到高并发,在检测到用户中奖后,应该检查一下奖品是否存在,没了就直接返回没中奖或者次一级奖品
     *      最后才将中奖结果返回
     */
}

// 概率比例
/* 接下来我们通过PHP配置奖项。 */
$data = array(
    array(
        "prize" => "平板电脑", "prob" => 1
    ),
    array(
        "prize" => "数码相机", "prob" => 3
    ),
    array(
        "prize" => "音箱设备", "prob" => 5
    ),
    array(
        "prize" => "8G优盘", "prob" => 20
    ),
    array(
        "prize" => "10Q币", "prob" => 200
    ),
    array(
        "prize" => "下次没准就能中噢", "prob" => 771
    )
);

foreach ($data as $key => $val) {
    $probability[$key] = $val["prob"];
}
$n = get_rand($probability);
$res['yes'] = $data[$n]["prize"];//$res['yes'] =$data[$n][0];

unset($data[$n]); // 将中奖项从数组中剔除,剩下未中奖项 
shuffle($data); // 将其它奖项顺序打乱

$func = create_function('$x', 'return $x["prize"];');

//$res['no'] = array_map(function($x){return $x[0];}, $data);  // 除了中奖外的其他数据
$res['no'] = array_map($func, $data);  // 除了中奖外的其他数据

print_r($res);
Copy after login

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477247.htmlTechArticle/** * 概率算法 * @param array $probability * @return integer|string */function get_rand($probability) { // 概率数组的总概率精度 $max = array_sum($probability); foreac...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!