随机页面生成,不包括已经在php中生成的选项


Random page generation excluding already generated options in php

我想要实现的是做一个网页,每次从MySQL数据库生成不同的内容。但是当我使用rand()函数时,一些选项可能会重复。所以我要做的是让rand()函数带有动态数组"exceptions"当网页内容生成时,每次都会更新,因此每个选项只显示给用户一次。

假设我有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"每次更新

是否有办法通过使用会话或其他选项来做到这一点?我不想使用另一个MySQL表。我希望它是快速和简单的

使用会话。会话用于数据持久化。像这样启动PHP文件:

<?php session_start();
//your code

将异常保存在会话变量中:

$_SESSION['exceptions']='exceptions Array';

每当用户访问一个页面时,将其添加到会话中。

假设你想给它加上'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;

这个一般性的问题以前已经回答过了。参见如何生成唯一随机数列表?为每个可能的页面分配一个编号,并使用适当的方法选择一个。