【问题标题】:php include random file with no repeat on pageloadphp包含随机文件,页面加载不重复
【发布时间】:2013-07-27 08:54:05
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您的代码 sn-p 应该可以完美运行吗?我不明白你的问题?
  • 对不起,我只在标题中写了这个,php 包含随机文件,在页面加载时没有重复。目前它有时会重复相同的文件。
  • 那么你应该将你的 $fictional 存储在 _SESSION 中并在存在时使用它,如果不使用你在 OP 中的代码

标签: php random include glob


【解决方案1】:

您可以使用会话 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) 的内容,并将那个列表存储在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] );

?>

【讨论】:

  • 错误表明$fictional[$index] 是一个空字符串,并且可能与glob 有关。注释掉包含行并添加var_dump( $fictional );。其中一个条目可能是空的。还要记住,代码 sn-p 并不是要复制/粘贴,而是更多地指导您朝着正确的方向前进。它不一定普遍适用。
猜你喜欢
  • 2014-01-10
  • 2015-01-06
  • 2015-05-24
  • 2015-09-01
  • 1970-01-01
  • 2015-04-02
  • 2018-04-09
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多