代码没有问题,但是在某些模板上没有。
以下是它的工作原理:
我将一组模板存储到会话中,并且只有在会话为空时才将它们随机播放。每次重新加载页面时,我都会弹出会话元素。因此,每次在页面中包含模板时,它都会从数组中弹出
这里的问题,在某些模板上,array_pop
函数在页面重新加载时弹出数组的2个元素(包含的模板+另一个)。
我试图在“有问题”的模板上删除一些代码,但我找不到解决方案。
我需要一些帮助来确定这个问题。
session_start();
$templates = array("t1.php","t2.php","t3.php"); #list of templates paths
if (!isset($_SESSION['templates']) || empty($_SESSION['templates'])) {
shuffle($templates); #shuffle them
$_SESSION['templates'] = $templates; #store them in sesssion
}
$currentTemplate = array_pop($_SESSION['templates']); #pops one on each page reload
include $currentTemplate; #includes the next template of the array
#on each page reload an element will be popped out and the next one will be included, the issue, is that sometimes two elements-templates are popped out of the array.
我检测到它通过以下代码弹出两个元素:
foreach($_SESSION['templates'] as $key=>$value)
{
echo 'The value of session['."'".$key."'".'] is '."'".$value."'".' <br />';
}
不重新加载
会话['0']的值是't3.php'
会话['1']的值是't2.php'
重新加载1:
在某些模板上我的代码工作正常,我再说一遍。我不知道发生了什么:)
答案 0 :(得分:2)
编辑#3 - 离线讨论后
原来JS正在向PHP脚本发起第二个请求(在后台),该脚本正在减少会话中存储的模板。
具体来说,正是预加载器循环遍历了对index.php发出额外请求的图像。
img = document.images;
jax = img.length;
for(var i=0; i<jax; i++) {
console.log(img[i].src);
}
11:38:39.711 VM322:5 http://plrtesting.herokuapp.com/index.php **这一个
11:38:39.711 VM322:5 https://i.imgur.com/gu9bfbD.gif
结束修改
代码完全按照您要求的方式执行。
$currentTemplate = array_pop($_SESSION['templates']);
您删除,而不是检索最终元素并将其分配给您的变量。每次重新加载页面时,数组都是popping
1个元素。这就是为什么你看到它随着时间减少。
您需要检索。如果你想要最后一个元素:
session_start();
$templates = array("t1.php","t2.php","t3.php"); #list of templates paths
if (!isset($_SESSION['templates']) || empty($_SESSION['templates'])) {
shuffle($templates); #shuffle them
$_SESSION['templates'] = $templates; #store them in sesssion
}
$currentTemplate = end((array_values($_SESSION['templates'])));
编辑#1 - 在每次加载页面时随机播放
请注意,有多种方法可以随机化模板。看看这种方式 - Get random item from array。
session_start();
$templates = array("t1.php","t2.php","t3.php"); #list of templates paths
// Commented out the if statement so it shuffles on each page load.
//if (!isset($_SESSION['templates']) || empty($_SESSION['templates'])) {
shuffle($templates); #shuffle them
$_SESSION['templates'] = $templates; #store them in sesssion
//}
$currentTemplate = end((array_values($_SESSION['templates'])));
var_dump($currentTemplate);
编辑#2 - 不确定是否清除,但您的代码正在循环剩余的元素;不是弹出的元素。