gpt4 book ai didi

PHP:从数组中进行非重复选择

转载 作者:行者123 更新时间:2023-12-02 22:16:03 26 4
gpt4 key购买 nike

在我的 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 中选择的号码。

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_keyarray_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;

关于PHP:从数组中进行非重复选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com