PHP中獎概率的抽獎算法程序代碼
<?php
//id為獎次,prize為中獎信息,v為中獎概率
$prize_arr = array(
'0' => array('id' => 1, 'prize' => '1 ', 'v' => 1),
'1' => array('id' => 2, 'prize' => '2 ', 'v' => 2),
'2' => array('id' => 3, 'prize' => '3 ', 'v' => 5),
'3' => array('id' => 4, 'prize' => '4 ', 'v' => 10),
'4' => array('id' => 5, 'prize' => '5 ', 'v' => 15),
'5' => array('id' => 6, 'prize' => '6 ', 'v' => 67),
);
foreach ($prize_arr as $key => $val)
{
$arr[$val['id']] = $val['v'];
}
$rid = get_rand($arr); //根據概率獲取獎項id
switch($rid)
{
case $rid==1:one();break;
case $rid==2:two();break;
case $rid==3:three();break;
case $rid==4:four();break;
case $rid==5:five();break;
case $rid==6:six();break;
}
/**
* 根據概率獲取中獎號碼
*/
function get_rand($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;
}
function one()
{
echo 'one------1';
}
function two()
{
echo 'two------2';
}
function three()
{
echo 'three------3';
}
function four()
{
echo 'four------4';
}
function five()
{
echo 'five------5';
}
function six()
{
echo 'six------6';
}
?>