从 array_rand 中排除选举

Exclude elections from array_rand

我发现这个 php 代码会随机生成 select 一个介于 1 和 9 之间的值,但不包括数组 $exclude 中的值。有效。

$exclude = array(1,2,3);
while(in_array(($x = rand(1,9)), $exclude));
echo $x;

现在我想 select 数组 $items 中的一个字母(从 'a' 到 'h'),但不包括 $exclude 中的字母(从 'a' 到 'c')。我使用以下代码:

$items = array("a", "b", "c", "d", "e", "f", "g", "h");
$exclude = array("a", "b", "c");
$rkey = array_rand($items);
while(in_array(($election = $items[$rkey]), $exclude));
echo $election;

问题: 这有效,但在刷新多次后,浏览器停止工作并无限期地继续加载。它不显示任何错误。

$rkey 只计算一次。您可以将代码替换到 while 循环中:

<?php

$items = array("a", "b", "c", "d", "e", "f", "g", "h");
$exclude = array("a", "b", "c");
while(in_array(($election = $items[array_rand($items)]), $exclude));
echo $election;

Teh Playground!

请注意 PHP 有 array_diff 内置功能,它做同样的事情。

$arrDiff=array_diff($items,$exclude);
echo $arrDiff[array_rand($arrDiff)];

或者更简单的方法是使用名为 array_diff() 的内置 PHP 函数,它 returns 通过从主列表,如:

$items = array("a", "b", "c", "d", "e", "f", "g", "h");
$exclude = array("a", "b", "c");

$nItems = array_diff($items, $exclude);
$rkey = array_rand($nItems);

$election = $nItems[$rkey];