PHP随机数没有重复

问题描述 投票:0回答:1

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

我有以下代码:

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

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

php random
1个回答
2
投票

使用混洗数组的想法很好,只需将其存储在会话变量中:

session_start();
if (!isset($_SESSION["numbers"]) || !count($_SESSION["numbers"])) {
    $_SESSION["numbers"] = range(1, 99);
    shuffle($_SESSION["numbers"]);
}
$next = array_pop($_SESSION["numbers"]);
© www.soinside.com 2019 - 2024. All rights reserved.