Home > Backend Development > PHP Tutorial > PHP example code to implement lottery

PHP example code to implement lottery

小云云
Release: 2023-03-21 14:04:01
Original
5067 people have browsed it

This article mainly shares with you the example code of php to implement lottery. We first share the code algorithm with you, hoping to help you.

Algorithm:

<?php function get_rand($proArr) { 
    $result = &#39;&#39;; 

    //概率数组的总概率精度 
    $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; 
}
Copy after login

Set prizes:

$prize_arr = array( 
    &#39;0&#39; => array(&#39;id&#39;=>1,&#39;prize&#39;=>&#39;平板电脑&#39;,&#39;v&#39;=>1), 
    &#39;1&#39; => array(&#39;id&#39;=>2,&#39;prize&#39;=>&#39;数码相机&#39;,&#39;v&#39;=>5), 
    &#39;2&#39; => array(&#39;id&#39;=>3,&#39;prize&#39;=>&#39;音箱设备&#39;,&#39;v&#39;=>10), 
    &#39;3&#39; => array(&#39;id&#39;=>4,&#39;prize&#39;=>&#39;4G优盘&#39;,&#39;v&#39;=>12), 
    &#39;4&#39; => array(&#39;id&#39;=>5,&#39;prize&#39;=>&#39;10Q币&#39;,&#39;v&#39;=>22), 
    &#39;5&#39; => array(&#39;id&#39;=>6,&#39;prize&#39;=>&#39;下次没准就能中哦&#39;,&#39;v&#39;=>50), 
);foreach ($prize_arr as $key => $val) { 
    $arr[$val[&#39;id&#39;]] = $val[&#39;v&#39;]; //将$prize_arr放入数组下标为$prize_arr的id元素,值为v元素的数组中} 

$rid = get_rand($arr); //根据概率获取奖项id $res[&#39;yes&#39;] = $prize_arr[$rid-1][&#39;prize&#39;]; //获取中奖项 unset($prize_arr[$rid-1]); //将中奖项从数组中剔除,剩下未中奖项 shuffle($prize_arr); //打乱数组顺序 for($i=0;$i<count($prize_arr);$i++){ 
    $pr[] = $prize_arr[$i][&#39;prize&#39;]; 
} 
$res[&#39;no&#39;] = $pr; 
echo json_encode($res);  

 ?>
Copy after login

The code can be run directly

Related recommendations:

js to implement lottery System function code sharing

php implementation of lottery probability algorithm code

PHP lottery function example

The above is the detailed content of PHP example code to implement lottery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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