PHP随机数不重复

时间:2019-02-16 13:11:19

标签: php random

似乎是重复的标题,但我访问了所有链接,但没有页面帮助我。

我有以下代码:

//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);

..但我不知道该如何整合:( 谢谢!

1 个答案:

答案 0 :(得分:2)

您的想法是将数组改组为好,只需将其存储在会话变量中即可:

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