文件夹中的随机文件(无重复)


Random file from folder (no repetition)

所以我使用以下代码从文件夹中拉取一个随机文件,我想这样做,这样就再也没有机会拉出当前文件了(即:连续两次看到相同的图像/文档)。

我该怎么做?提前感谢!

function random_file($dir = 'destinations')
{
    $files = glob($dir . '/*.*');
    $file = array_rand($files);
    return $files[$file];
}

将上次查看的文件名存储在 cookie 或会话中。

以下是使用 cookie 的方法:

function random_file($dir = 'destinations') {
    $files = glob($dir . '/*.*');
    if (!$files) return false;
    $files = array_diff($files, array(@$_COOKIE['last_file']));
    $file = array_rand($files);
    setcookie('last_file', $files[$file]);
    return $files[$file];
}
$picker = new FilePicker();
$picker->randomFile();
$picker->randomFile(); // never the same as the previous

--

class FilePicker
{
    private $lastFile;
    public function randomFile($dir = 'destinations')
    {
        $files = glob($dir . '/*.*');
        do {
            $file = array_rand($files);
        } while ($this->lastFile == $file);
        $this->lastFile = $file;
        return $files[$file];
    }
}

本质上:存储数组中使用的每个文件的名称; 每次抽取新名称时,检查数组中是否已存在该名称。

in_array()将帮助您。 array_push()将有助于填充"已用文件"数组。

您可以将数组设置为静态数组,以便在调用函数时使列表可用(而不是使用全局变量)。

如果要

以随机顺序显示一组固定的文件,然后将所有文件名读入数组,随机排列数组然后从头到尾使用数组。