【问题标题】:Copying x random values from one array to another PHP将 x 个随机值从一个数组复制到另一个 PHP
【发布时间】:2016-06-07 22:48:35
【问题描述】:

我正在尝试使用以下代码将 5 个随机值从一个数组复制到另一个数组。问题是 3 或 4 个值被复制,而 1 或 2 总是被复制为 null。我不确定我的代码中的问题是什么。

if (count($potential_matches_in_area) >= 5) {
  for ($x = 0; $x < 5; $x++) {

  $index = mt_rand(0, count($potential_matches_in_area) - 1);
  $new_matches[$x] = $potential_matches_in_area[$index];
  unset($potential_matches_in_area[$index]);

  } 

【问题讨论】:

    标签: php arrays for-loop random


    【解决方案1】:

    问题是,这一行:

    mt_rand(0, count($potential_matches_in_area) - 1);
    

    你可以得到重复的键,第一次运行时运行正常,但是一旦未设置的键再次出现,你会得到一个未定义的索引。为什么不直接使用array_rand

    if (count($potential_matches_in_area) >= 5) {
        for ($x = 0; $x < 5; $x++) {
            $index = array_rand($potential_matches_in_area);
            $new_matches[$x] = $potential_matches_in_area[$index];
            unset($potential_matches_in_area[$index]);
        } 
    }
    

    您只会得到仍然可用的当前密钥。

    【讨论】:

    • 我读到 array_rand 效率较低,并且在分发时偶尔会产生奇怪的结果,但如果这是唯一的方法,我会使用它
    • @mankee 如果你想坚持你的mt_rand,你需要汇总你自己的使用mt_rand的自定义函数,然后对应你的数组
    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 2013-11-08
    • 2022-07-05
    • 1970-01-01
    • 2016-04-10
    相关资源
    最近更新 更多