PHP中防止数组和字符串重复
我将php模板随机化,以将它们包含在网页中。每次用户重新加载网页时,都会出现一个新的随机模板PHP中防止数组和字符串重复,php,random,Php,Random,我将php模板随机化,以将它们包含在网页中。每次用户重新加载网页时,都会出现一个新的随机模板 array\u rand的问题每次用户重新加载网页时,都会返回一个随机字符串,同一模板可能会反复显示 例如,假设用户重新加载页面3次。他可以获得以下模板: template1.php、template1.php、template2.php $items = array("template1.php","template2.php","template3.php"); #templates array $
array\u rand的问题
每次用户重新加载网页时,都会返回一个随机字符串,同一模板可能会反复显示
例如,假设用户重新加载页面3次。他可以获得以下模板:
template1.php、template1.php、template2.php
$items = array("template1.php","template2.php","template3.php"); #templates array
$a = $items[array_rand($items,1)]; #randomize templates
include $a; #including randomized template
我希望用户以随机顺序查看所有模板。例如
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
在调用rand过程之前,可以将in if语句与$\u 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;
为此,您需要保存访问者已经加载的模板。这可以保存在会话中,例如:
//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;
您可以在
if
语句中结合使用$\u SESSION[]
变量来存储上一页,并在调用rand过程之前从数组中省略上一页,或者将模板无序排列并存储在一个会话中?“所有模板以随机顺序”是;-)的确切定义但是你必须决定当你的模板用完时你想要发生什么。Shuffle可能仍然会显示上一页,阅读操作guys@pokeybit是的,我正在将其编辑到我的评论中。为了确保在重置阵列之前至少访问所有页面一次,使用上面/下面的@Philipp Maurer答案我尝试了你的代码,但在看到所有模板之前我得到了相同的模板。它不符合要求。请接受此答案,因为它更符合您编辑的要求mine@GragasIncoming是的,我调整了答案,你能评论一下PHP5支持的代码吗<代码>$visitedTemplates=$\会话['visitedTemplates']??[];@GragasIncoming否,但根据我已经做的评论阅读必要的更改并不是那么困难:-)我提供的信息应该足以让您创建解决方案。@GragasIncoming是研究三元if运算符的一个良好开端。