从PHP数组中获取随机值,但要使其唯一
发布时间:2020-12-13 13:10:31 所属栏目:PHP教程 来源:网络整理
导读:我想从数组中选择一个随机值,但尽可能保持它的唯一性. 例如,如果我从4个元素的数组中选择一个值4次,则所选值应该是随机的,但每次都不同. 如果我从4个元素的相同数组中选择它10次,那么显然会复制一些值. 我现在有这个,但我仍然得到重复的值,即使循环运行4次:
我想从数组中选择一个随机值,但尽可能保持它的唯一性.
例如,如果我从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不起作用.
为了使它与你在那里保持一致: <?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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |