这是来自here的后续问题。
代码运行良好,它将链接发送到博客文章。缺点是我可能会两次或太频繁地落入同一个帖子。
header("Location: ".$posts[array_rand ($posts)][1]);
我需要它不要每20分钟落在同一个帖子上,如果用完帖子然后说:“没有选择。请在20分钟后回来。”我尝试使用像这样的cookie:
$rlink = $posts[array_rand ($posts)][1];
setcookie("rlink", "$rlink", time()+1200);
if ($rlink == $_COOKIE["rlink"]) {
header('Location: http://localhost/randommyblog.php');
} else
{
header("Location: ".$rlink);
}
可能很明显,这里的问题是我每次都更换cookie“rlink”,使前一个没用。
请帮忙吗?
答案 0 :(得分:2)
尝试这样的事情,当我按原样测试时工作:
$posts = array("hello", "world", "it's", "me" );
$len_posts = count( $posts );
$set_indices = @$_COOKIE['rlink'];
$rand = mt_rand( 0, $len_posts - 1 ); //Select a random index from the post
if( !empty( $set_indices ) )
{
$set_indices = array_map( "intval", explode( ",", $set_indices ) );
$len_indices = count( $set_indices );
if( $len_indices >= $len_posts )
{
die("no posts for you");
}
else
{
while( in_array( $rand, $set_indices, TRUE ) ) //Calculate a new index that has not been shown.
{
$rand = mt_rand( 0, $len_posts - 1 );
}
}
}
else
{
$set_indices = array();
}
array_push( $set_indices, $rand );
setcookie( "rlink", implode( ",", $set_indices ), time()+1200 ); //Set cookie of the shown indices like "3,0,1" for example.
echo $posts[$rand];