drt3751 2011-09-04 22:16
浏览 46
已采纳

rand()函数没有按预期工作(嵌套在foreach()中)?

The idea is that a max and a minimum value are posted, and then a random number between the two is generated.

For example, $mins = array(30,40,50,60) and $maxs = array(40,50,60,70), and then my code:

foreach($mins as $minkey => $maxval) {
    foreach($maxs as $maxkey => $maxval) {
            $hits[$maxkey] = rand($minval,$maxval);
    }
}

If I then var_dump($mins), var_dump($maxs) and var_dump($hits), I get:

array(4) { [1]=> string(2) "30" [2]=> string(2) "40" [3]=> string(2) "50" [4]=> string(2) "60" } array(4) { [1]=> string(2) "40" [2]=> string(2) "50" [3]=> string(2) "60" [4]=> string(2) "70" } array(4) { [1]=> int(27) [2]=> int(36) [3]=> int(19) [4]=> int(41) }

I thought the fact that $maxs and $mins contained string values, while $hits containing integers (i.e. rand() requires integer inputs ?) might be the issue so I updated my loop to become:

foreach($mins as $minkey => $minval) {
    foreach($maxs as $maxkey => $maxval) {
        $minval = (int)$minval;
        $maxval = (int)$maxval;
            $hits[$maxkey] = rand($minval,$maxval);
    }
}

But on var_dump($mins), var_dump($maxs) and var_dump($hits), this was dumped:

array(4) { [1]=> string(2) "30" [2]=> string(2) "40" [3]=> string(2) "50" [4]=> string(2) "60" } array(4) { [1]=> string(2) "40" [2]=> string(2) "50" [3]=> string(2) "60" [4]=> string(2) "70" } array(4) { [1]=> int(0) [2]=> int(47) [3]=> int(0) [4]=> int(55) }

Does anyone have any idea why this isn't working as expected?

Any thoughts/answers/comments would be very much appreciated :)!

  • 写回答

4条回答 默认 最新

  • dongrong9053 2011-09-04 22:23
    关注

    Do you want to do that? if yes, you can't have one loop in another...

    for($i = 1; $i <= sizeof($mins); $i++) {
      $hits[$i] = rand($mins[$i], $maxs[$i]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀