如何只返回一次随机字符串


How to return random string only once?

我到处寻找答案,但似乎在任何地方都找不到。

<?php
$f_contents = file("x.txt"); 
$line = $f_contents[rand(0, count($f_contents) - 1)];
echo($line);
?>

目前,我在每次页面加载时都会得到随机结果,但只需要返回一次字符串。我正在使用Wordpress,所以我更希望只有在创建页面时才能这样做。

有什么想法吗?

您可以使用uniqid()函数中内置的PHP:

http://php.net/manual/en/function.uniqid.php

创建页面时,您需要向页面添加一条元信息。

你可以通过创建自己的插件来做到这一点。

添加一个包含posts ID的选项,并且仅在该选项还不存在时设置该选项。

function random_option($id, $file){
if(get_option("rand_option".$id))
     return get_option("rand_option".$id);
$f_contents = file($file); 
$value = $f_contents[rand(0, count($f_contents) - 1)];
add_option( "rand_option".$id, $value );
return $value;
}

然后称之为:

echo random_option(get_the_ID(), "file.txt");