PHP选择时间的阵列项目比例? [英] PHP Choose Array Item Percentage of The Time?

查看:106
本文介绍了PHP选择时间的阵列项目比例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图想出一个办法有一个特定的阵列项目选择的时候一定比例。因此,可以说:

I am trying to figure out a way to have a particular array item chosen a certain percentage of the time. So lets say:

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

现在我将如何去有选择ITEM1可以说的40%的时间。我知道这可能是真的很容易,但我似乎无法环绕它我的头今天。

Now how would I go about having item1 chosen lets say 40% of the time. I know this is probably really easy but I can't seem to wrap my head around it today.

推荐答案

通过这些百分比:

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

选择1和100之间的随机数:

Choose a random number between 1 and 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

  • 确保 $机会具有相同的密钥作为输入数组(即 array_keys array_combine

  • use array_sum() instead 100
  • assure that $chances has the same keys as the input array (i.e. with array_keys and array_combine)

这篇关于PHP选择时间的阵列项目比例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆