2013-07-26 62 views
1

我目前使用mt_rand在每次加載頁面時顯示指定文件夾中的隨機文件。php包含隨機文件,頁面加載時不重複

經過大量的搜索後,我想我需要創建一個數組,然後洗牌數組,但不知道如何去做這件事。

我發現的大多數例子都使用了一個數組,然後回顯結果,因爲我試圖包含結果。

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

http://php.net/manual/en/function.shuffle.php –

+0

您的代碼段應該很好地工作?我不明白你的問題? – bwoebi

+0

可能重複[For random order no no repeating numbers](http://stackoverflow.com/questions/10886704/for-in-random-order-no-repeating-numbers) – Herbert

回答

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也存儲在索引此列表中的當前位置,當它到達終點,我們重新洗牌和重新開始。

我知道這一切聽起來可能有點混亂,所以也許這華麗的圖將幫助: Gorgeous Diagram

&hellip;或者一些代碼:

<?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]); 

?> 
+0

錯誤表明'$ fictional [$ index]'是一個空字符串,可能以某種方式與'glob'相關。註釋掉include行並添加'var_dump($ fictional);'。其中一個條目可能是空的。另外請注意,代碼片段並不打算複製/粘貼,但更多的指導方針可以讓您朝着正確的方向前進。這不一定是普遍適用的。 – Herbert