druzuz321103 2017-10-29 12:02 采纳率: 100%
浏览 191

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

is there a way that when I use the random function to get a list of random strings to display, it will stay even after i refreshed the page?

Such as this code:

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;
    }

It only get the first value from the array and store into the session.

  • 写回答

3条回答 默认 最新

  • doulandai0641 2017-10-29 12:09
    关注

    Solution:

    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)
    

    If you want multiple items:

    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 )
    
    评论

报告相同问题?