我目前有一段代码从数组中选择随机值,但我想阻止它选择重复值。我怎样才能做到这一点?到目前为止,这是我的代码:
$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>';
}
答案 0 :(得分: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 :(得分: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>';
}