php 转盘红包概率 可刷新运行 刷新

大转盘红包概率

代码:

function getPrize($prizes) {   
    $result=[];
    $weights = array_sum(array_column($prizes,'w'));        
    foreach ($prizes as $k => $prize) {   
        $randNum = mt_rand(1, $weights);   
        if ($randNum <= $prize['w']) {   
            $result = $prize;   
            break;   
        } else {   
            $weights -= $prize['w'];   
        }         
    }     
    return $result;   
} 
$prizes = array(   
    array('id'=>1,'name'=>'特等奖','w'=>1),
    array('id'=>2,'name'=>'一等奖','w'=>5),
    array('id'=>3,'name'=>'二等奖','w'=>10),
    array('id'=>4,'name'=>'三等奖','w'=>12),
    array('id'=>5,'name'=>'四等奖','w'=>22),
    array('id'=>6,'name'=>'没中奖','w'=>50)
); 
var_export(getPrize($prizes));

输出:

array (
  'id' => 6,
  'name' => '没中奖',
  'w' => 50,
)