## 概率性抽奖(lottery_raffle)
~~~
//chance为抽到概率,数值越小,概率越小
$arr = [
['name'=>'1000元手机','chance'=>'1'],
['name'=>'100元代金券','chance'=>'10'],
['name'=>'10元代金券','chance'=>'100'],
['name'=>'谢谢参与','chance'=>'700'],
];
/**
* 抽奖概率算法
* @param array $prizeArr 奖品数组
* @param string $index 概率键名
* @return mixed 抽到的奖品
*/
function lottery_raffle($prizeArr,$index='chance')
{
$result = '';
$randArr = [];
$i = 1;
foreach($prizeArr as $item){
$randArr[$i] = $item[$index];
$i++;
}
//概率数组的总概率精度
$proSum = array_sum($randArr);
//概率数组循环
foreach ($randArr as $key => $val) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $val) {
$result = $key;
break;
} else {
$proSum -= $val;
}
}
return $prizeArr[$result];
}
~~~
## 示例
~~~
//输出抽奖结果,例如:array ( 'name' => '谢谢参与', 'chance' => '700', )
var_export(lottery_raffle($arr));
~~~