0

我需要四个不重复的多个随机数。所以我拿了一个数组。你能帮我在哪里做错了吗?我有 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;
?>
4

2 回答 2

5

我建议将完整的数组/集合随机化一次,然后将其分解为块并存储这些块(例如,在 $_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));
}
于 2013-03-10T10:42:06.213 回答
3

你可以这样做:

<?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
}
于 2013-03-10T10:40:29.313 回答