在会话中存储随机数组以在页面重新加载时循环

时间:2015-01-24 00:04:04

标签: php loops session cookies reload

我有一个PHP函数,可以在会话中存储随机数组。每次重新加载页面时,它都会循环遍历数组。当到达数组的末尾时,它会生成一个新的随机数组来循环。

是否可以使用第一次访问时生成的完全相同的随机数组,而不是生成新的随机数组?

// Init array
$files = array();

// Init session
session_start();

// 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 ) {
    // Reload with all files
    $files = array(1, 2, 3, 4, 5);
}
else {
    // Use the files that are left
    $files = $_SESSION['FILES'];
}

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

// Include random file
print_r($files[$selectedFile]);

// Remove random file from array
unset($files[$selectedFile]);

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

1 个答案:

答案 0 :(得分:0)

使用另一个会话,可能称为$_SESSION['FILES_BACKUP'];

当您的阵列变空时,将备份会话复制到主阵列。

// Init array
$files = array();


// Init session
session_start();

// 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(!isset($_SESSION['FILES_BACKUP'])) {
        // Reload with all files
        echo 'no backup';
        $files = array(1, 2, 3, 4, 5);
    } else {
        echo 'backup';
        $_SESSION['FILES'] = $_SESSION['FILES_BACKUP'];
        $files = $_SESSION['FILES_BACKUP'];
    } 
    } else {
        // Use the files that are left
        $files = $_SESSION['FILES'];
    }

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

// Include random file
print_r($files[$selectedFile]);

// Remove random file from array
unset($files[$selectedFile]);

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