2012-11-06 149 views
0

我目前有一段代碼是從數組中選擇隨機值,但我想阻止它選擇重複值。我怎樣才能做到這一點?這是到目前爲止我的代碼:防止數組選擇重複值

$facilities = array("Blu-ray DVD Player","Chalk board","Computer", "Projector", 
"Dual data projector", "DVD/Video"); 

for($j = 0; $j < rand(1, 3); $j++) 
    { 
    $fac = print $facilities[array_rand($facilities, 1)] . '<br>'; 
    } 

回答

5

我想你應該看看array_rand

$facilities = array("Blu-ray DVD Player","Chalk board","Computer","Data projector","Dual data projector","DVD/Video"); 
$rand = array_rand($facilities, 2); 
           ^----- Number of values you want 

foreach ($rand as $key) { 
    print($facilities[$key] . "<br />"); 
} 
+1

+1你又是 – GBD

+0

爲什麼它不能用array_rand($ facilities,1);'。我已經試過\t \t \t'$ rand = array_rand($ facilities,rand(1,3));'但它不起作用 – methuselah

+0

'echo $ facilities [array_rand($ facilities)];''''''''''只有一個元素 – Baba

2

您可以從array_rand()通過指定數量返回作爲第二個參數返回多個隨機密鑰。

$keys = (array) array_rand($facilities, rand(1, 3)); 
shuffle($keys); // array_rand() returns keys unshuffled as of 5.2.10 

foreach ($keys as $key) { 
    echo $facilities[$key] . '<br>'; 
} 
+1

唯一值得指出的是,如果rand(1,3)是1,這將失敗地失敗。 – deceze

+1

@deceze現在不會。 – salathe