Generating random results by weight in PHP?

前端 未结 12 699
青春惊慌失措
青春惊慌失措 2020-11-22 07:35

I know how to generate a random number in PHP but lets say I want a random number between 1-10 but I want more 3,4,5\'s then 8,9,10\'s. How is this possible? I would post wh

12条回答
  •  隐瞒了意图╮
    2020-11-22 08:05

    /**
     * @param array $weightedValues
     * @return string
     */
    function getRandomWeightedElement(array $weightedValues)
    {
        $array = array();
    
        foreach ($weightedValues as $key => $weight) {
            $array = array_merge(array_fill(0, $weight, $key), $array);
        }
    
        return $array[array_rand($array)];
    }
    

    getRandomWeightedElement(array('A'=>10, 'B'=>90));

    This is very easy method. How get random weighted element. I fill array variable $key. I get $key to array $weight x. After that, use array_rand to array. And I have random value ;).

提交回复
热议问题