我想要实现的是制作一个网页,每次从 MySQL DB 生成不同的内容。但是当我使用 rand() 函数时,一些选项可以重复。所以我想做的是使 rand() 函数具有动态数组“异常”,每次生成网页内容时都会更新,因此每个选项只向用户显示一次。
假设我有 5 种不同的选择: 1,2,3,4,5
当 rand() 函数下次选择 3 时,结果将没有机会得到 3..
function randWithout($from, $to, array $exceptions) {
sort($exceptions);
$number = rand($from, $to - count($exceptions));
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++;
} else {
break;
}
}
return $number;
}
$exceptions = array("3","4");
$random = randWithout(1, $num_rows, $exceptions);
这就是我想要的,但我希望数组“$exceptions”每次都更新。
有没有办法通过使用 session 或其他一些选项来做到这一点?我不想使用另一个 MySQL 表。我希望它既快速又简单。
最佳答案
使用 session 。 session 用于数据持久化。像这样启动你的 php 文件:
<?php session_start();
//your code
将异常保存在 session 变量中:
$_SESSION['exceptions']='exceptions Array';
每次用户访问页面时,将其添加到 session 中。
假设您要向其添加“5”。
她的更新代码
<?php session_start();
function randWithout($from, $to) {
global $exceptions;
sort($exceptions);
$number = rand($from, $to - count($exceptions));
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++;
} else {
break;
}
}
return $number;
}
if(isset($_SEEION['exceptions'])){
$exceptions =$_SESSION['exceptions'];
}
$random = randWithout(1, $num_rows);
$exceptions[]=$random;
$_SESSION['exceptions']=$exceptions;
关于php - 随机页面生成不包括 php 中已生成的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14033325/