首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在PHP中防止array_rand字符串重复

问在PHP中防止array_rand字符串重复
EN

Stack Overflow用户
提问于 2018-04-30 15:32:45
回答 2查看 123关注 0票数 1

我随机化的php模板,以包括在网页上。每次用户重新加载网页时,都会出现一个新的随机化模板。

array_rand的问题是,它会在用户每次重新加载网页时返回一个随机字符串,并且可能会一次又一次地显示相同的模板。

例如,假设用户重新加载页面3次。他可能会得到以下模板:template1.php, template1.php, template2.php

我想让用户看到一个随机顺序的所有模板。例如,template3.php,template2.php,template1.php

代码语言:javascript
复制
$items = array("template1.php","template2.php","template3.php"); #templates array
$a = $items[array_rand($items,1)]; #randomize templates

include $a; #including randomized template
EN

回答 2

Stack Overflow用户

发布于 2018-04-30 15:38:25

在调用rand过程之前,可以将if语句与$_SESSION[]变量结合使用,以存储前一页并省略数组中的前一页

代码语言:javascript
复制
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;
票数 1
EN

Stack Overflow用户

发布于 2018-04-30 15:43:02

要使其正常工作,您需要保存访问者已经加载的模板。这可以保存在会话中,例如:

代码语言:javascript
复制
//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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50095895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档