1

我目前正在使用 mt_rand 在每次加载页面时显示来自指定文件夹的随机文件。

经过大量搜索后,我认为我需要创建一个数组,然后对数组进行洗牌,但不知道该怎么做。

我发现的大多数示例都使用数组,然后在我尝试包含结果时回显结果。

<?php
$fict = glob("spelling/*.php");
$fictional = $fict[mt_rand(0, count($fict) -1)];
include ($fictional);
?>
4

1 回答 1

2

您可以使用会话 cookie 来保存随机的、非重复的文件列表。实际上,为了安全起见,会话 cookie 应该只将索引列表存储到文件数组中。

例如,假设我们在一个数组中有以下文件列表:

index           file
----------------------------
  0      spelling/file1.txt
  1      spelling/file2.txt
  2      spelling/file3.txt
  3      spelling/file4.txt

我们可以创建一个索引数组,例如 array(0,1,2,3),将它们打乱以获得类似的东西array(3,2,0,1),并将列表存储在 cookie 中。然后,随着我们遍历这个随机索引列表,我们得到序列:

spelling/file4.txt
spelling/file3.txt
spelling/file1.txt
spelling/file2.txt

cookie 还将当前位置存储在这个索引列表中,当它到达末尾时,我们重新洗牌并重新开始。

我意识到这一切可能听起来有点令人困惑,所以也许这个华丽的图表会有所帮助: 华丽的图表

……或者一些代码:

<?php

$fictional = glob("spelling/*.php");    // list of files
$max_index = count($fictional) - 1;
$indices = range( 0, $max_index );      // list of indices into list of files

session_start();

if (!isset($_SESSION['indices']) || !isset($_SESSION['current'])) {

    shuffle($indices);
    $_SESSION['indices'] = serialize($indices);
    $_SESSION['current'] = 0;           // keep track of which index we're on

} else {

    $_SESSION['current']++;             // increment through the list of indices
                                        // on each reload of the page

}

// Get the list of indices from the session cookie
$indices = unserialize($_SESSION['indices']);

// When we reach the end of the list of indices,
// reshuffle and start over.
if ($_SESSION['current'] > $max_index) {

    shuffle($indices);
    $_SESSION['indices'] = serialize($indices);
    $_SESSION['current'] = 0;

}

// Get the current position in the list of indices
$current = $_SESSION['current'];

// Get the index into the list of files
$index = $indices[$current];

// include the pseudo-random, non-repeating file
include( $fictional[$index] );

?>
于 2013-07-27T13:45:49.503 回答