簡體   English   中英

PHP中的多個隨機數而無需重復?

[英]multiple random numbers in php without repeating?

我需要四個不重復的隨機數。 所以我為此做了一個數組。 我做錯了什么可以幫我嗎? 我有24個問題以隨機順序出現,每頁需要4個問題,為此,我接受了一個數組“ $ questions”,最初將25個問題插入其中。 然后,當我得到不在數組中的隨機數時,我便用該隨機數替換了該特定索引。 我做錯了什么?

<?php
$questions = array(0);
for ($i = 0; $i < 24 ; $i++) {
$questions[$i]= ",";
}

$a="1";
$b="2";
$c="3";
$d="4";
//$a=rand(0, 23);
while(!in_array($a=rand(0, 23), $questions)) {
    $replacements = array($a => $a);
    $questions = array_replace($questions, $replacements);
    $max = sizeof($questions);
    if ($max==4) {
        break;
    }
    echo "<br>a=".$a."<br>";
    for ($i = 0; $i < 24 ; $i++) {
        echo $questions[$i];
    }
}
//echo "a=".$a."b=".$b."c=".$c."d=".$d;
?>

我建議將整個數組/集合隨機化一次,然后將其分解成塊並存儲這些塊(例如,在$ _SESSION中)。

<?php
$questions = data(); // get data
shuffle($questions); // shuffle data
$questions = array_chunk($questions, 4); // split into chunks of four
// session_start();
// $_SESSION['questions'] = $questions;
// on subsequent requests/scripts do not re-create $questions but retrieve it from _SESSION

// print all sets
foreach($questions as $page=>$set) {
    printf("questions on page #%d: %s\n", $page, join(', ', $set));
}

// print one specific set
$page = 2;
$set = $questions[$page];
printf("\n---\nquestions on page #%d: %s\r\n", $page, join(', ', $set));


// boilerplate function: returns example data
function data() {
    return array_map(function($e) { return sprintf('question #%02d',$e); }, range(1,24));
}

您可以執行以下操作:

<?php

$archive = array();
$span = 23;
$amount = 4;
$i = 0;
while (true) {
    $number = rand(0, $span);             // generate random number
    if (in_array($number, $archive)) {    // start over if already taken
        continue;
    } else {
        $i++;
        $archive[] = $number;             // add to history
    }
    /*
      do magic with $number
    */
    if ($i == $amount) break;             // opt out at 4 questions asked
}

暫無
暫無

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

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