【问题标题】:Store random array in session cookie and loop through it将随机数组存储在会话 cookie 中并循环遍历它
【发布时间】:2023-03-16 05:46:01
【问题描述】:

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

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

【问题讨论】:

  • 您提供了另一个答案的链接,并说它不适合您。它是如何“不工作”的?错误是什么?
  • 我没有发现任何错误,但没有显示任何内容……

标签: php session-cookies shuffle


【解决方案1】:

这是你要找的吗?

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

?>

【讨论】:

  • 非常感谢!恐怕,代码对我来说不能正常工作。我认为选择所有文件后重新加载有问题。 viper-7.com/DsxTP8
  • 我用错了array_rand ;) 但现在应该可以了
  • 假设重载之前的最后一个索引是4,如何保证重载之后的第一个索引不是4?
  • 感谢修改,YANTHO!和聪明的问题,d0c! — 是否有可能在所有文件都被选中后重新开始第一次访问网站时随机生成的完全相同的顺序?
  • 是的,我认为最简单的方法是在第一次访问时使用随机位置的值创建一个数组,并使用该数组来重置正在使用的数组。
猜你喜欢
  • 2011-01-20
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
相关资源
最近更新 更多