2014-07-12 22 views
0

我有一個數組$files包含一個目錄中的php文件列表。每次加載時,其中一個文件應隨機包含在頁面中。因此,我洗了陣列shuffle($files);在會話cookie中存儲隨機數組並通過它循環

爲了避免同一個php include被加載到一行中,我希望將shuffle數組存儲在會話cookie中,因此每次頁面刷新時都會有一個循環遍歷數組。當數組結束時,應該生成一個新的混洗陣列,...

我發現this但它沒有爲我工作。 這是我到目前爲止有:

PHP

// Get files from directory and store them in an array 
$files = glob("teaser-images/*.php"); 

// Start session 
session_start(); 

// Randomize array and store it in a session cookie 
shuffle($files); 

// If there’s already a cookie find the corresponding index and loop trough the array each refresh 
if (isset($_SESSION['last_index'])) { 
    $_SESSION['last_index'] = … 

    // If the end of the array is reached shuffle it again and start all over 
} 

// If there’s no cookie start with the first value in the array   
else { 
    $_SESSION['last_index'] = … 
} 

// Include the php file 
include($random_file); 
+0

您提供了另一個答案的鏈接,並表示它不適用於您。它如何「不起作用」?什麼是錯誤? – naomik

+0

我發現沒有錯誤,但沒有顯示任何內容... – user1706680

回答

0

這是你想要的?

<?php 

// Initialize the array 
$files = array(); 

session_start(); 

var_dump($_SESSION['FILES']); 
// Check if this is the first time visit or if there are files left to randomly select 
if(!isset($_SESSION['FILES']) OR count($_SESSION['FILES']) == 0){ 
    // If its the first time visit or all files have already been selected -> reload with all files 
    $files = array(1, 2, 3, 4, 5); 
    echo("first time visit/reloaded/"); 
} 
else{ 
    // Use the files that are left 
    $files = $_SESSION['FILES']; 
    echo("use the files that are left/"); 
} 

// Get a random file 
$selectedFile = array_rand($files); 
var_dump($selectedFile); 

//include the random file 
print_r($files[$selectedFile]); 
// Remove randome file from array 
unset($files[$selectedFile]); 

// Set the session with the remaining files 
$_SESSION['FILES'] = $files; 

?> 
+0

你能解釋一下代碼嗎? – user1706680

+0

非常感謝!我擔心,代碼對我來說工作不正常。我認爲當所有文件被選中時重新加載都有問題。 http://viper-7.com/DsxTP8 – user1706680

+0

我用array_rand錯誤;)但現在它應該工作 – YANTHO

相關問題