概率抽奖
<?php $prize_arr = array( '0' => array('id' => 1, 'title' => '二等奖', 'v' => 20), '1' => array('id' => 2, 'title' => '三等奖', 'v' => 100), '2' => array('id' => 3, 'title' => '四等奖', 'v' => 100), '3' => array('id' => 4, 'title' => '未中奖', 'v' => 1000), ); foreach ($prize_arr as $key => $val) { $arr[$val['id']] = $val['v']; } //$arr= [1=>'phone',2=>'note'] //print_r($arr);die; $prize_id = getRand($arr); //根据概率获取奖品id $data['msg'] = ($prize_id == 4) ? 0 : 1; //如果为0则没中 $data['prize_title'] = $prize_arr[$prize_id - 1]['title']; //中奖奖品 echo json_encode($data); exit; //以json数组返回给前端 function getRand($proArr) { //计算中奖概率 $rs = ''; //z中奖结果 $proSum = array_sum($proArr); //概率数组的总概率精度 //概率数组循环 foreach ($proArr as $key => $proCur) { $randNum = mt_rand(1, $proSum); if ($randNum <= $proCur) { $rs = $key; break; } else { $proSum -= $proCur; } } unset($proArr); return $rs; } ?>