1、随机函数
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; }
2、实现过程,如不希望被抽中,可将概率设置为0
$prize_arr = array( '0' => array('id'=>1,'prize'=>'平板电脑','v'=>1), '1' => array('id'=>2,'prize'=>'数码相机','v'=>1), '2' => array('id'=>3,'prize'=>'音箱设备','v'=>1), '3' => array('id'=>4,'prize'=>'4G优盘','v'=>1), '4' => array('id'=>5,'prize'=>'10Q币','v'=>1), '5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>95), ); $arr=[]; foreach ($prize_arr as $key => $val) { $arr[$key] = $val['v']; } $rid = get_rand($arr); //根据概率获取数组下标 $res['yes'] = $prize_arr[$rid]['prize']; //中奖项 var_dump($res); }