dongyu3967 2013-11-07 19:10
浏览 18
已采纳

回应随机数组

Here's the code I'm using:

<?php
$input = array("Test1", "Test1", "Test1", "Test1","Test2");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]];
?>

Bascially I want to echo Test1 and Test2 randomly - BUT I want Test1 to show up 4x more than Test2 does.

I'm guessing that by adding it in 4 times more than Test2, it should show up 4 times more - is that code correct or should I be doing it a different way?

  • 写回答

5条回答 默认 最新

  • dougang1965 2013-11-07 19:16
    关注

    If we modify your code slightly to run in a loop:

    $input = array("Test1", "Test1", "Test1", "Test1", "Test2");
    $results = array("Test1" => 0, "Test2" => 0);
    
    for ($i = 0; $i < 1000; $i++) {
        $rand_keys = array_rand($input);
        $results[$input[$rand_keys]]++;
    }
    
    var_export($results);
    

    I get results that look like this:

    array (
      'Test1' => 807,
      'Test2' => 193,
    )
    

    That looks pretty close to four times as much to me!

    Note that I have changed your array_rand call so it only receives one result at a time, because otherwise look at what happens:

    $rand_keys = array_rand($input, 2); // get two results 
    echo $input[$rand_keys[0]];         // echo the first one
    

    The results appear in the order they are in in the original array. In this case, that means that Test2, when it appears, will always be last, so will never show up in your results.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题