我正试图建立一个网站,以随机的方式引导您浏览八个页面,而不重复这些页面,例如: 首先是'filmpje4.php',其中包含指向'filmpje8.php'的链接,导致'filmpje3.php'等等,直到所有八页都被访问过。
我浏览过几个网站,但我找到的代码似乎没有用。我一直在重复......
我尝试过的代码示例:
$links = array('<a href="filmpje1.php">filmpje1</a>', [...]'<a href="filmpje8.php">filmpje8</a>');
// get users visited links to an array
$visited_links = explode('|', $_SESSION['visited_links']);
// remove visited links from links array
foreach($visited_links as $visited_link) {
unset($links[array_search($visited_link, $links)]);
}
// get a random link from unvisited links
$link = $links[rand(0, count($links)-1)];
// add the selected link to visited array
$visited_links[] = $link;
// save visited links to user session as | separated string
$_SESSION['visited_links'] = implode('|', $visited_links);
echo $link;
答案 0 :(得分:1)
<?php
session_start();
if (!isset($_SESSION["visited_pages"])) { $_SESSION["visited_pages"] = array(); }
$links = array("file1.php","file2.php","file3.php","file4.php");
$nonvisited_links = array_values(array_diff($links,$_SESSION["visited_pages"]));
$next_index = mt_rand(0,sizeof($nonvisited_links)-1);
$_SESSION["visited_pages"][] = $next_page = $nonvisited_links[$next_index];
?>
<a href="localhost/<?php echo $next_page; ?>">visit!!</a>
答案 1 :(得分:0)
尝试一下:
$tmp = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
$visited = array('b', 'f', 'h'); // get from session
if(count($tmp) == count($visited))
{
$visited = array();
// reset session
}
while(true)
{
$item = $tmp[rand(0, count($tmp) - 1)];
if(!is_array($item, $visited))
break;
}
$visited[] = $item;
// set session
答案 2 :(得分:0)
而不是校对你编写的代码,这是一个新代码。
代码可以/应该进行适当的优化测试,但它可以解决问题。
<?php
$all_page_links = ('a.php','b.php','c.php','d.php',
'e.php','f.php');
$visited_page_links = $_SESSION['visited_page_links'];
//eg data: 'c.php','f.php'
$can_visit_pages = array_diff($all_page_links,$visited_page_links);
if(!isset($_GET['next_page']) //this is the first visit
{
$can_visit_index = rand(0, count($can_visit_pages) - 1);
$current_page = $can_visit_pages[$can_visit_index];
unset($can_visit_pages[$can_visit_index]);
$visited_page_links[] = $current_page;
$next_page = $can_visit_pages[rand(0, count($can_visit_pages) - 1)];
include($current_page); //include the contents of the current
//page (or redirect). $current_page code will
//have the link to the $next_page.
}
else
if(isset($_GET['next_page']))
{
//TO-Do - pre-check if the page has been visited.
$current_page = $_GET['next_page'];
$visited_page_links[] = $current_page;
$current_page_index = array_search($current_page,$can_visit_pages);
unset($can_visit_pages[$current_page_index]);
$next_page = $can_visit_pages[rand(0, count($can_visit_pages) - 1)];
include($current_page); //include the contents of the current
//page (or redirect). $current_page code will
//have the link to the $next_page.
}
$_SESSION['visited_page_links'] = $visited_page_links;
?>