我在PHP中有两个数组:大小。小数组中的所有值都包含在大数组中。我需要从大数组中获取随机值,但它不会与小数组的任何值匹配。类似的东西:
$big = array('2','3','5','7','10');
$small = array('2','5','10');
$random = '3'; // it's not 2, 5 or 10
答案 0 :(得分:3)
$big = array('2','3','5','7','10');
$small = array('2','5','10');
$nums = array_diff($big,$small);//numbers in big that are not in small
$rand = array_rand($nums); //get a random key from that set
$val = $nums[$rand]; //get the value associated with that random key
答案 1 :(得分:0)
$bigs = ['1', '2', '3', '5', '10'];
$small = ['1', '5', '10'];
foreach($bigs as $big)
{
if(!in_array($big, $small))
{
echo $big. "\n";
}
}
答案 2 :(得分:-1)
您可以使用array_diff()
来确定差异 - 并从结果数组中选择一个随机数(使用mt_rand()
):
$arrDiff = array_values(array_diff($big, $small));
$random = $arrDiff[mt_rand(0, count($arrDiff)-1)];
注意:array_values()
方法确保只将值复制到数组$arrDiff
,因此来自0...n-1
的索引将填充值。array_diff()
将保持索引位置,因此可能没有索引0
,1
或其他任何内容,如@ Undefined-Variable所述。