在開發的時候也會經常處理一些抽獎的活動頁面。吾愛編程把寫的抽獎算法分享給大家,有需要的可以直接使用,具體代碼如下:
<?php
header("Content-type: text/htm; charset=utf-8");
$prize_arr = array(
'0' => array('id'=>1,'prize'=>'平板電腦','v'=>1),
'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'=>'10Q幣','v'=>22),
'5' => array('id'=>6,'prize'=>'下次沒准就能中哦','v'=>50),
);
foreach ($prize_arr as $key => $val) {
$arr[$val['id']] = $val['v'];
}
echo "<pre>";
print_r($arr);
$rid = get_rand($arr); //根據概率獲取獎項id
$res['yes'] = $prize_arr[$rid-1]['prize']; //中獎項
unset($prize_arr[$rid-1]); //將中獎項從數組中剔除,剩下未中獎項
shuffle($prize_arr); //打亂數組順序
for($i=0;$i<count($prize_arr);$i++){
$pr[] = $prize_arr[$i]['prize'];
}
$res['no'] = $pr;
// echo "<pre>";
// var_dump($res);die;
function get_rand($proArr) {
$result = '';
//概率數組的總概率精度
$proSum = array_sum($proArr);
//概率數組循環
foreach ($proArr as $key => $proCur) {
$randNum = mt_rand(1, $proSum);
echo '隨機數上限制:'.$proSum;
if ($randNum <= $proCur) {
$result = $key;
break;
} else {
$proSum -= $proCur;
}
echo "隨機數:".$randNum;
echo "<=:".$proCur;
}
echo "結果:".$result;die;
unset ($proArr);
return $result;
}
?>
*