适用于抽奖、随机广告等需要按概率从一组数据中取出一个的场景。
代码实例:
function getProbabilityPrizeId($prize_info)
{
$prize_arr = [];
foreach ($prize_info as $key => $val) {
$prize_arr[$val['id']] = bcmul($val['probability'], '1000', 0);
}
//概率数组的总概率精度
$proSum = array_sum($prize_arr);
//概率数组循环
$randNum = mt_rand(1, $proSum);
foreach ($prize_arr as $key => $proCur) {
$randNum -= $proCur;
if ($randNum <= 0) {
$prizeId = $key;
break;
}
}
return $prizeId;
}
$prize_arr = [
['id' => 1, 'prize' => '平板电脑', 'probability' => 1],
['id' => 2, 'prize' => '数码相机', 'probability' => 5],
['id' => 3, 'prize' => '音箱设备', 'probability' => 10],
['id' => 4, 'prize' => '4G优盘', 'probability' => 12],
['id' => 5, 'prize' => '10Q币', 'probability' => 22],
['id' => 6, 'prize' => '下次没准就能中哦', 'probability' => 50],
];
var_dump(getProbabilityPrizeId($prize_arr));