当前位置:网站首页>PHP implements lottery according to probability

PHP implements lottery according to probability

2022-07-07 03:59:00 Pointer loves me again

One 、 Ideas

Think about how many values to fill in the array according to the possibility , for instance 30% The risk of , Just fill the array with 30 Of this prize id

Two 、 Implementation code

$data = [
    [
        'id' => 1,
        'name' => ' Thank you for your patronage ',
        'probability' => 80 //  Lottery probability 
    ],
    [
        'id' => 2,
        'name' => '10 Yuan cash ',
        'probability' => 18 //  Lottery probability 
    ],
    [
        'id' => 3,
        'name' => '100 Yuan cash ',
        'probability' => 2 //  Lottery probability 
    ],
];
$list = [];
foreach ($data as $key=>$v){
    
    $list = array_merge($list, array_fill(0, $v['probability'], $v['id']));// Generate prize array 
}
shuffle($list);// Disorder array order 
$key = array_rand($list,1);// Get array random subscript 
//  Return the prize id,  The latter can be based on the prize id Realize specific other businesses 
return $list[$key];

If you have any questions, please contact me !

原网站

版权声明
本文为[Pointer loves me again]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062117262435.html