php 抽獎概率 隨機數
阿新 • • 發佈:2019-01-08
<?php $prize_arr = array( '0' => array('id' => 1, 'title' => 'iphone5s', 'v' => 5), '1' => array('id' => 2, 'title' => '聯絡筆記本', 'v' => 10), '2' => array('id' => 3, 'title' => '音箱裝置', 'v' => 20), '3' => array('id' => 4, 'title' => '30GU盤', 'v' => 30), '4' => array('id' => 5, 'title' => '話費50元', 'v' => 10), '5' => array('id' => 6, 'title' => 'iphone6s', 'v' => 15), '6' => array('id' => 7, 'title' => '謝謝,繼續加油哦!~', 'v' => 10), ); foreach ($prize_arr as $key => $val) { $arr[$val['id']] = $val['v']; } $prize_id = getRand($arr); //根據概率獲取獎品id $data['msg'] = ($prize_id == 7) ? 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; } ?>