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>'; 
   } 
4

2 回答 2

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 />");
}
于 2012-11-06T12:21:16.590 回答
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>';
}
于 2012-11-06T12:21:54.937 回答