Laravel rand()排除数字



我的代码看起来像:

$test = Hosting::where('status', 'active')->where('node', 'Full')->select('port')->get()->toArray();
while( in_array( ($n = mt_rand(1312,1319)), array($test) ) );
echo $n;

$测试结果为:

array:2 [▼
0 => array:1 [▼
"port" => 1315
]
1 => array:1 [▼
"port" => 1318
]

我想排除$test结果中的随机数,现在是(13151318(,我该怎么做?

您可以在此处使用do while。我还添加了勇气来获得一个扁平的端口阵列。

$test = Hosting::where('status', 'active')
->where('node', 'Full')
->pluck('port')
->toArray();
do {
$n = mt_rand(1312, 1319);
} while (in_array($n, $test));
echo $n;

我建议在循环之前检查可用端口,以防止无限循环,例如

if (empty(array_diff(range(1312, 1319), $test))) {
throw new Exception('No port available.');
}

使用查询生成器:

$hosts = Hosting::where('status', 'active')
->where('node', 'Full')
->select('port')
->whereNotIn('port' mt_rand(1312,1319))
->get();

采用Eloquent Collection方法:

$hosts = Hosting::where('status', 'active')
->where('node', 'Full')
->select('port')
->get()
->whereNotIn('port' mt_rand(1312,1319));

最新更新