Php 防止数组生成相同链接的最佳方法?
这是我的后续问题 代码工作得很好,它随机链接到博客文章。缺点是,我可能会两次或太频繁地陷入同一个帖子Php 防止数组生成相同链接的最佳方法?,php,Php,这是我的后续问题 代码工作得很好,它随机链接到博客文章。缺点是,我可能会两次或太频繁地陷入同一个帖子 header("Location: ".$posts[array_rand ($posts)][1]); 我需要它不要每20分钟就落在同一个帖子上超过一次,如果没有帖子了,就说:“没有选择,20分钟后再来。”。我试着用曲奇饼这样做: $rlink = $posts[array_rand ($posts)][1]; setcookie("rlink", "$rlink", time()+120
header("Location: ".$posts[array_rand ($posts)][1]);
我需要它不要每20分钟就落在同一个帖子上超过一次,如果没有帖子了,就说:“没有选择,20分钟后再来。”。我试着用曲奇饼这样做:
$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”,使前一个变得无用
请给我一点帮助?试试这样的方法,在我按原样测试时效果很好:
$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];
这是可行的,而且近乎完美,当链接用完时,它会一直加载,并显示错误500。有没有办法回显“用完”而不是这个错误?@Sara,如果($len_index===$len_posts)块中有什么?您的帖子数组是一维0索引的吗?
echo“对不起,帖子已用完,20分钟后再来。”代码>但它没有显示这个回音,而是持续加载20秒左右,然后显示错误500。@Sara,如我的示例所示,执行die()
。让我来修正另一件事:P我将==
更改为=
,因为您的cookie的帖子比现有的多,所以循环是有限的。。你的cookie之所以有更多帖子,是因为你使用了echo
而不是die()
。现在它很完美了。非常感谢!:)