2013-03-10 26 views
0

我需要四个多个随机数而不重复。所以我拿了一个数组。你能帮我解决我犯错的地方吗?我有24个问题以随机顺序出现,每页需要4个问题,为此我带了一个数组“$ questions”,并最初插入了25个问题。那么当我得到一个不在数组中的随机数时,我将用随机数替换该特定索引。我在哪里做错了?在php中的多个随机数字没有重复?

<?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; 
?> 
+3

这是一个很多重复性代码。你有没有听说过[DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself)? – Zeta 2013-03-10 10:35:23

回答

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)); 
} 
+0

谢谢你的回答。但是我做错了? – 2013-03-10 10:49:50

+1

我真的不明白你在那里试过什么。也许你应该解释你的算法。 – VolkerK 2013-03-10 20:17:11

+0

终于我实现了,你的阿尔戈volkerk。谢谢。 – 2013-03-11 11:04:24

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 
} 
+0

..但我更喜欢VolkerK的解决方案。 – 2013-03-10 10:49:31

+0

嗯。我只是试图按照我的方式实施。我很感谢你们的答复。感谢@Volkerk并感谢你也 – 2013-03-10 10:54:07

+0

我在实施中做了什么错误? – 2013-03-10 10:54:47