将随机数组存储在会话cookie中并循环遍历它

时间:2014-07-12 19:52:18

标签: php session-cookies shuffle

我有一个数组$files,其中包含目录中的php文件列表。每次加载时,其中一个文件应随机包含在页面中。因此,我改组了数组shuffle($files);

为了避免连续加载相同的php include,我希望将shuffled数组存储在会话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);

1 个答案:

答案 0 :(得分: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;

?>