抽奖概率控制 (简便)

 /**
     * 根据给定概率随机选择一项
     * @param $itemArray array("奖项1","奖项2"....);
     * @param $chanceArray  array("10","50","40","70")  数组的一个参数/所有参数加起来 == 这项奖项的概率
     * @return int|null     返回$itemArray中被选中的索引,逻辑有错误时返回NULL
     */
    public static function pickOne($itemArray, $chanceArray = NULL){
       $index = NULL;
        if($itemArray){
            if(sizeof($itemArray) <= 0){
                return NULL;
            }
        }

        if($chanceArray){

            if(sizeof($chanceArray) <= 0 || sizeof($chanceArray) != sizeof($itemArray)){
                return NULL;
            }

            if(sizeof($chanceArray) == 1){
                return 0;
            }

            $fullChance = 0;
            foreach($chanceArray as $value){
                $fullChance += $value;
            }
            if($fullChance <= 0){
                return NULL;
            }

            //参数正常,给予默认的第一项
            $index = 0;

            $baseChance = 0;
            $ranum = rand(0, $fullChance - 1);
            for($i = 1 ; $i < sizeof($itemArray) ; $i++){
                if($ranum >= $baseChance && $ranum < ($baseChance + $chanceArray[$i])){
                    $index = $i;
                    break;
                }
                $baseChance += $chanceArray[$i];
            }
        }else{
            //参数正常,给予默认的第一项
            $index = 0;
            $index = rand(0, sizeof($itemArray) - 1);
        }

        return $index;
    }
原文地址:https://www.cnblogs.com/renshi/p/4334352.html