public function index(Request $request)
{
$prize_arr = array(
'0' => array('id' => 1, 'prize' => '奖品名称1', 'v' => 50),
'1' => array('id' => 2, 'prize' => '奖品名称2', 'v' => 10),
'2' => array('id' => 3, 'prize' => '奖品名称3', 'v' => 10),
'3' => array('id' => 4, 'prize' => '奖品名称4', 'v' => 30)
);
foreach ($prize_arr as $key => $val) {
$arr[$val['id']] = $val['v'];
}
$rid = $this->getRand($arr); //根据概率获取奖项id
return $prize_arr[$rid-1];//中奖数组
}
计算中奖概率
public function getRand($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;
}