2016-06-07 142 views
1

我想用下面的代码将5个随机值从一个阵列复制到另一个阵列。问题是3或4个值被复制,1或2总是被复制为null。我不确定我的代码中存在什么问题。将x个随机值从一个阵列复制到另一个阵列PHP

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

    } 

回答

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

你只会得到现在的钥匙,它仍然可用。

+0

我读过array_rand效率较低,并且偶尔会产生一些分发问题,但如果它是唯一的方法,我会使用它 – Alk

+0

@mankee如果你想坚持你的'mt_rand',你将需要使用'mt_rand'来卷起自己的自定义函数,然后对应于你的数组 – Ghost