PHP随机按百分比抽奖

2019-04-15 08:59:04

<?php
//计算中奖概率
function getRand($proArr){ 
    $rs = '';//中奖结果 
    $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; 
}

$prize_arr = array( 
    '0' => array('id' => 10, 'title' => 'iphone5s', 'v' => 5), 
    '1' => array('id' => 20, 'title' => '联系笔记本', 'v' => 10), 
    '2' => array('id' => 30, 'title' => '音箱设备', 'v' => 20), 
    '3' => array('id' => 40, 'title' => '30GU盘', 'v' => 30), 
    '4' => array('id' => 50, 'title' => '话费50元', 'v' => 10), 
    '5' => array('id' => 60, 'title' => 'iphone6s', 'v' => 15), 
    '6' => array('id' => 70, 'title' => '谢谢,继续加油哦!~', 'v' => 10), 
); 
$arr=array();
foreach ($prize_arr as $key => $val) { 
    $arr[$key+1] = $val['v']; 
}

echo '<pre />';
print_r($prize_arr);
print_r($arr);
//exit();

echo $prize_id = getRand($arr); //根据概率获取奖品id 

//$data['msg'] = ($prize_id == 7) ? 0 : 1; //如果为0则没中  
echo $data['prize_title'] = $prize_arr[$prize_id - 1]['title']; //中奖奖品 
//echo json_encode($data);//以json数组返回给前端
相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!