我目前正在使用mt_rand在每次加载页面时显示指定文件夹中的随机文件。
经过大量的搜索后,我想我需要创建一个数组,然后对数组进行洗牌,但不知道如何解决这个问题。
我发现的大多数例子都使用了一个数组然后回显结果,因为我试图包含结果。
<?php
$fict = glob("spelling/*.php");
$fictional = $fict[mt_rand(0, count($fict) -1)];
include ($fictional);
?>
答案 0 :(得分:2)
您可以使用会话Cookie来保存随机,不重复的文件列表。实际上,为了安全起见,会话cookie应该只将 indices 列表存储到一个文件数组中。
例如,假设我们在数组中有以下文件列表:
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)
的内容,并将 列表存储在其中饼干。然后,当我们浏览这个随机的索引列表时,我们得到序列:
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] );
?>