原文:http://blog.csdn.net/dongsg11200/article/details/24607877
php中獎機率算法,可用於刮刮卡,大轉盤等抽獎算法php
- <?php
- 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;
- }
- $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'];
- }
- $rid = get_rand($arr);
- $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;
- print_r($res);
- ?>