我随机化的php模板,以包括在网页上。每次用户重新加载网页时,都会出现一个新的随机化模板。
array_rand的问题是,它会在用户每次重新加载网页时返回一个随机字符串,并且可能会一次又一次地显示相同的模板。
例如,假设用户重新加载页面3次。他可能会得到以下模板:template1.php, template1.php, template2.php
我想让用户看到一个随机顺序的所有模板。例如,template3.php,template2.php,template1.php
$items = array("template1.php","template2.php","template3.php"); #templates array
$a = $items[array_rand($items,1)]; #randomize templates
include $a; #including randomized template发布于 2018-04-30 15:38:25
在调用rand过程之前,可以将if语句与$_SESSION[]变量结合使用,以存储前一页并省略数组中的前一页
session_start();
$items = array("template1.php","template2.php","template3.php");
if (($key = array_search($_SESSION['last_page'], $items)) !== false) {
unset($items [$key]);
} //taken from https://stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key
$a = $items[array_rand($items,1)];
$_SESSION['last_page'] = $a;
include $a;发布于 2018-04-30 15:43:02
要使其正常工作,您需要保存访问者已经加载的模板。这可以保存在会话中,例如:
//At the beginning of your script
session_start();
//... Some code
//Read visited paths from session or create a new list.
//?? works only in PHP7+. Use isset()?: instead of ?? for previous versions
$visitedTemplates = $_SESSION['visitedTemplates'] ?? [];
//Your list, just slightly changed syntax. Same thing
$originalList = [
"template1.php",
"template2.php",
"template3.php"
];
//Remove all paths that were already visited from the randomList
$randomList = array_diff($originalList, $visitedTemplates);
//You need to check now if there are paths left
if (empty($randomList)) {
//The user did load all templates
//So first you set the list to choose a new template from to the list of all templates
$randomList = $originalList;
//And then you delete the cache of the visited templates
$visitedTemplates = [];
}
//Show the user the next one
$randomTemplate = $randomList[array_rand($randomList)];
include $randomTemplate;
//Now we need to save, that the user loaded this template
$visitedTemplates[] = $randomTemplate;
//And we need to save the new list in the session
$_SESSION['visitedTemplates'] = $visitedTemplates;https://stackoverflow.com/questions/50095895
复制相似问题