页面刷新后,随机函数的php值保持不变

时间:2017-10-29 12:02:17

标签: php random

有没有一种方法,当我使用随机函数来获取要显示的随机字符串列表时,即使我刷新页面后它仍会保留?

比如这段代码:

session_start();
$a = array("red","green","blue","yellow","brown");


if ( ! isset($_SESSION['rand_val']) ) {
     $_SESSION['rand_val'] = array_rand(array_flip($a)); 
}
try{
        $db = $conn->prepare("Select Column from Table where `xColumn` = XX");
        $db->execute();

        while($row=$db->fetch(PDO::FETCH_OBJ)) { 
       //if returned 5 values from DB, then randomly generate 5 values.

            echo $row->Column, "<br>";

            echo ($_SESSION['rand_val']), "<br>";
        }


} catch (PDOException $e) {
        echo "Error: ".$e;
    }

它只从数组中获取第一个值并存储到会话中。

3 个答案:

答案 0 :(得分:2)

救援会议

$key = $_SESSION['key'] ?? ( $_SESSION['key'] = array_rand($a) );
echo $key;

请记住,这仅适用于您有会话的情况,所以如果您不这样做,您还需要先运行session_start();

答案 1 :(得分:1)

解决方案:

session_start();

$a = array("red","green","blue","yellow","brown");

if ( ! isset($_SESSION['rand_val']) ) {
    $_SESSION['rand_val'] = array_rand(array_flip($a));
}


echo $_SESSION['rand_val']; // green (or other values in array)

如果您想要多个项目:

session_start();

$a = array("red","green","blue","yellow","brown");

if ( ! isset($_SESSION['rand_val']) ) {
    $_SESSION['rand_val'] = array_rand(array_flip($a), 2); // Specify how many random value you want from array
}


print_r($_SESSION['rand_val']); // Array ( [0] => blue [1] => yellow )

答案 2 :(得分:0)

另一种可能性是使用rand()重写代码,然后事先使用srand()

将其播种