簡體   English   中英

PHP隨機數不重復

[英]PHP random number no repeat

似乎是重復的標題,但我訪問了所有鏈接,但沒有頁面對我有所幫助。

我有以下代碼:

//Check if form was submitted
if($_POST){
    $number = $_POST['number'];
    $selected_choice = $_POST['choice'];
    $next=$number+1;
    $total=4;

    //Get total number of questions
    $query="SELECT * FROM `questions` LIMIT 4";
    $results = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $total=$results->num_rows;

    //Get correct choice
    $q = "select * from `choices` where question_number = $number and is_correct=1";
    $result = $mysqli->query($q) or die($mysqli->error.__LINE__);
    $row = $result->fetch_assoc();
    $correct_choice=$row['id'];



    //compare answer with result
    if($correct_choice == $selected_choice){
        $_SESSION['score']++;
    }

    if($number == $total){
        header("Location: final.php");
        exit();
    } else {
            header("Location: formular1.php?n=".$next."&score=".$_SESSION['score']);
    }
}

我需要做的是在提交表單時獲得一個隨機數,但是該數字必須唯一,並且在會話結束之前不要重復。

我努力了:

$number = range(1, 99);
shuffle($number);

..但我不知道該如何整合:(謝謝!

將數組改組后的想法很好,只需將其存儲在會話變量中即可:

session_start();
if (!isset($_SESSION["numbers"]) || !count($_SESSION["numbers"])) {
    $_SESSION["numbers"] = range(1, 99);
    shuffle($_SESSION["numbers"]);
}
$next = array_pop($_SESSION["numbers"]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM