doushi1957 2013-03-12 06:12
浏览 32

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');

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.

  • 写回答

1条回答 默认 最新

  • drkbpwk609294 2013-03-12 06:27
    关注

    With these percentages:

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

    Choose a random number between 1 and 100:

    $rand = rand(1,100);
    

    And select the according array item:

    | 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];
        }
    }
    

    Possible improvement for a more general solution:

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

报告相同问题?

悬赏问题

  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表