从PHP数组中获取随机值,但要使其唯一

前端之家收集整理的这篇文章主要介绍了从PHP数组中获取随机值,但要使其唯一前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从数组中选择一个随机值,但尽可能保持它的唯一性.

例如,如果我从4个元素的数组中选择一个值4次,则所选值应该是随机的,但每次都不同.

如果我从4个元素的相同数组中选择它10次,那么显然会复制一些值.

我现在有这个,但我仍然得到重复的值,即使循环运行4次:

@H_502_7@$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不起作用.

为了使它与你在那里保持一致:

@H_502_7@<?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; }

或者少一行的例子:

@H_502_7@<?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; }

猜你在找的PHP相关文章