在PHP中防止array_rand字符串重复

时间:2018-04-30 07:32:45

标签: php random

我随机化了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

2 个答案:

答案 0 :(得分:1)

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

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 :(得分:0)

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

//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;