我想从数组中选择一个随机值,但尽可能保持它的唯一性.
例如,如果我从4个元素的数组中选择一个值4次,则所选值应该是随机的,但每次都不同.
如果我从4个元素的相同数组中选择它10次,那么显然会复制一些值.
我现在有这个,但我仍然得到重复的值,即使循环运行4次:
$arr = $arr_history = ('abc','def','xyz','qqq'); for($i = 1; $i < 5; $i++){ if(empty($arr_history)) $arr_history = $arr; $selected = $arr_history[array_rand($arr_history,1)]; unset($arr_history[$selected]); // do something with $selected here... }
你几乎把它弄好了.问题是未设置($arr_history [$selected]);线. $selected的值不是键,但实际上是一个值,因此unset不起作用.
原文链接:https://www.f2er.com/php/136584.html为了使它与你在那里保持一致:
<?PHP $arr = $arr_history = array('abc','qqq'); for ( $i = 1; $i < 10; $i++ ) { // If the history array is empty,re-populate it. if ( empty($arr_history) ) $arr_history = $arr; // Select a random key. $key = array_rand($arr_history,1); // Save the record in $selected. $selected = $arr_history[$key]; // Remove the key/pair from the array. unset($arr_history[$key]); // Echo the selected value. echo $selected . PHP_EOL; }
或者少一行的例子:
<?PHP $arr = $arr_history = array('abc',re-populate it. if ( empty($arr_history) ) $arr_history = $arr; // Randomize the array. array_rand($arr_history); // Select the last value from the array. $selected = array_pop($arr_history); // Echo the selected value. echo $selected . PHP_EOL; }