javaphp
$prize_arr = array(
'0' => array('id'=>1,'prize'=>'平板電腦','v'=>3),
'1' => array('id'=>2,'prize'=>'數位相機','v'=>5),
'2' => array('id'=>3,'prize'=>'音箱裝置','v'=>10),
'3' => array('id'=>4,'prize'=>'4G優盤','v'=>12),
'4' => array('id'=>5,'prize'=>'Q幣10元','v'=>20),
'5' => array('id'=>6,'prize'=>'下次沒準就能中哦','v'=>50),
);
foreach ($prize_arr as $key => $val) {
$arr[$val['id']] = $val['v'];
}
$rid = getRand($arr); /*根據機率擷取獎項id*/
$res['msg'] = ($rid==6)?0:1;
$res['prize'] = $prize_arr[$rid-1]['prize']; /*中獎項*/
echo json_encode($res);exit;
/*計算機率*/
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;
}
?>