[英]PHP: Non-Repeating Selection From an Array
在我的PHP脚本中,我有一个$ data变量,其中包含一个数组,该数组可能具有各种元素。
该脚本随机选择一个数组元素,并将其输出到浏览器:
# count number of elements in $data
$n = count($data);
# pick a random number out of the number of elements in $data
$rand = rand(0, ($n - 1));
# output a random element
echo '<p> . trim($data[$rand]) . '</p>';
问题:我想改进该脚本,以便在用完数组元素之前不会再次输出相同的数组元素。 例如,如果一个数组包含编号为0到9的元素,并且脚本选择了数组元素#4,则我希望它记住这一点,并且下次脚本运行时,将元素#4排除在外。
可能可以通过许多不同的方式完成此操作,但是我正在寻找最简单,最优雅的解决方案,并且感谢PHP专家的帮助。
保存在用户会话中已经选择的号码。
session_start();
$n = count($data);
// If the array isn't initialized, or we used all the numbers, reset the array
if( !isset( $_SESSION['used_nums']) || count( $_SESSION['used_nums']) == $n) {
$_SESSION['used_nums'] = array();
}
do{
$rand = rand(0, ($n - 1));
} while( isset( $_SESSION['used_nums'][$rand]));
echo '<p>' . trim($data[$rand]) . '</p>';
$_SESSION['used_nums'][$rand] = 1;
或者,也许更聪明的方法是使用array_intersect_key
和array_rand
:
session_start();
$n = count($data);
// If the array isn't initialized, or we used all the numbers, reset the array
if( !isset( $_SESSION['used_nums']) || count( $_SESSION['used_nums']) == $n) {
$_SESSION['used_nums'] = array();
}
$unused = array_intersect_key( $data, $_SESSION['used_nums'];
$rand = array_rand( $unused);
echo '<p>' . trim($unused[$rand]) . '</p>';
$_SESSION['used_nums'][$rand] = 1;
您可以重新排列数组,然后简单地对其进行迭代:
shuffle($data);
foreach ($data as $elem) {
// …
}
如果您不想更改数组的顺序,则可以简单地随机排列数组的键:
$keys = array_keys($data);
shuffle($keys);
foreach ($keys as $key) {
// $data[$key]
}
您可以使用会话来存储到目前为止已使用的索引。 尝试这个。
session_start();
$used = &$_SESSION['usedIndexes'];
// used all of our array indexes
if(count($used) > count($data))
$used = array();
// remove the used indexes from data
foreach($used as $index)
unset($data[$index]);
$random = array_rand($data);
// append our new index to used indexes
$used[] = $random;
echo '<p>', trim($data[$random]) ,'</p>';
$selection=$x[$randomNumber];
unset($x[$randomNumber]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.