做项目的时候涉及到抽奖概率的设置,以下是php实现中奖抽奖概率的计算算法,供大家参考
一、中奖概率方法:可以看到设置了每个中奖概率,合计中奖概率为100%
<?php
public function gl(){
$prize_arr = [
'0' => ['id' => 1, 'prize' => '奖品1', 'v' => 20],
'1' => ['id' => 2, 'prize' => '奖品2', 'v' => 10],
'2' => ['id' => 3, 'prize' => '奖品3', 'v' => 20],
'3' => ['id' => 4, 'prize' => '奖品4', 'v' => 5],
'4' => ['id' => 5, 'prize' => '奖品5', 'v' => 19],
'5' => ['id' => 6, 'prize' => '奖品6', 'v' => 5],
'6' => ['id' => 7, 'prize' => '奖品7', 'v' => 10],
'7' => ['id' => 8, 'prize' => '奖品8', 'v' => 10],
];
foreach ($prize_arr as $key => $val) {
$arr[$val['id']] = $val['v'];
}
$rid = $this->get_prize($arr); //根据概率获取奖项id
$data = $prize_arr[$rid-1];
return json($data);
}
二、对概率进行计算
<?php
public function get_prize($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;
}
?>