从一个PHP数组中获取随机值,但不匹配另一个数组


Get random from one PHP array but not match from another

PHP中有两个数组:大数组和小数组。小数组中的所有值都包含在大数组中。我需要从大数组中获得随机值,但它不会与小数组的任何值匹配。比如:

$big = array('2','3','5','7','10');
$small = array('2','5','10');
$random = '3'; // it's not 2, 5 or 10
$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
$bigs = ['1', '2', '3', '5', '10'];
    $small = ['1', '5', '10'];
    foreach($bigs as $big)
    {
        if(!in_array($big, $small))
        {
            echo $big. "'n";
        }
    }

您可以使用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所述。