Generating random results by weight in PHP?

前端 未结 12 854
青春惊慌失措
青春惊慌失措 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:17

    You can use weightedChoice from Non-standard PHP library. It accepts a list of pairs (item, weight) to have the possibility to work with items that can't be array keys. You can use pairs function to convert array(item => weight) to the needed format.

    use function \nspl\a\pairs;
    use function \nspl\rnd\weightedChoice;
    
    $weights = pairs(array(
        1 => 10,
        2 => 15,
        3 => 15,
        4 => 15,
        5 => 15,
        6 => 10,
        7 => 5,
        8 => 5,
        9 => 5,
        10 => 5
    ));
    
    $number = weightedChoice($weights);
    

    In this example, 2-5 will appear 3 times more often than 7-10.

提交回复
热议问题