进击的码农

按照概率得到数组下标

$proArr = [
        1=>'20',//设置得到下标1的概率是20%
        2=>'20',
        3=>'20',
        4=>'0',
        5=>'20',
        6=>'20',
        7=>'0',
        8=>'0',
        9=>'0',
        10=>'0',
    ];
public static 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;

}

回复

This is just a placeholder img.