【问题标题】:PHP Choose Array Item Percentage of The Time?PHP选择数组项的时间百分比?
【发布时间】:2013-03-12 06:12:50
【问题描述】:

我正在尝试找出一种方法来让特定的数组项在一定百分比的时间内被选中。所以让我们说:

$testArray = array('item1', 'item2', 'item3', 'item4', 'item5');

现在我将如何选择 item1 让我们说 40% 的时间。我知道这可能真的很容易,但我今天似乎无法理解它。

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    这些百分比:

    $chances = array(40,15,15,15,15);
    

    在 1 到 100 之间选择一个随机数:

    $rand = rand(1,100);
    

    并选择相应的数组项:

    | item1              | item2  | item3  | item4  | item5  |
    0                   40       55       70       85       100
    
    $ref = 0;
    foreach ($chances as $key => $chance) {
        $ref += $chance;
        if ($rand <= $ref) {
            return $testArray[$key];
        }
    }
    

    更通用的解决方案的可能改进:

    • 使用array_sum() 代替100
    • 确保$chances 具有与输入数组相同的键(即array_keysarray_combine

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多