PHP获取固定概率

public static  function getFixRand($weight) {
        if ((int)$weight < 0 || (int)$weight > 100) {
            return -1;
        }

        $weightArr = [
            1 => $weight,
            2 => 100-$weight,
        ];

        $result = '';

        //概率数组的总概率精度
        $sumWeight = array_sum($weightArr); //计算数组中元素的和
        $luckyNum = mt_rand(1, $sumWeight);
        //概率数组循环
        $beginCursor = $endCursor = 0;
        foreach ($weightArr as $id => $w) {
            $beginCursor = $endCursor;
            $endCursor += $w;

            if ($luckyNum > $beginCursor && $luckyNum <= $endCursor) {
                $result = $id;
                break;
            }
        }
        if ($result == 1) {
            return true;
        } else {
            return false;
        }
    }

原文地址:https://www.cnblogs.com/jiqing9006/p/10301163.html