我需要四个多个随机数而不重复.所以我拿了一个阵列.我能帮助我做错了吗?我有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;
?>
Run Code Online (Sandbox Code Playgroud)
我建议将整个数组/集随机化,然后将其分解成块并存储这些块(例如在$ _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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2832 次 |
| 最近记录: |