九宫格抽奖概率算法

$prizeList = [1=>["id"=>1,"name"=>'A',"chance"=>50],2=>["id"=>2,"name"=>'B',"chance"=>80],3=>["id"=>3,"name"=>'C',"chance"=>70]];
$arr = [1=>50,2=>80,3=>70];
$prize_id = get_rand($arr); //根据概率获取奖项id
function get_rand($proArr) {
    $result = '';

    //概率数组的总概率精度
    $proSum = array_sum($proArr);

    //概率数组循环
    $randNum = mt_rand(1, $proSum);
    $temp = 0;
    foreach ($proArr as $key => $proCur) {
        if ($randNum <= ($proCur+$temp)) {
            $result = $key;
            break;
        }
        else $temp +=$proCur;
    }
    unset ($proArr);

    return $result;
}

你可能感兴趣的:(php,概率算法,php概率算法)