【发布时间】:2023-03-22 03:58:01
【问题描述】:
我想获得有例外的随机数(例如,我想要一个从 500 到 550 的数字,而没有 505、512、525 等)。
我在这里找到了这样一个代码:
function randWithout($from, $to, array $exceptions) {
sort($exceptions); // lets us use break; in the foreach reliably
$number = rand($from, $to - count($exceptions)); // or mt_rand()
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++; // make up for the gap
} else {
break;
}
}
return $number;
}
如果我使用类似的东西:
$nr = randWithout(500, 550, array(505, 512, 525));
一切都很好,但是在数组中我想从mysql中放入元素,所以我创建了:
$query = mysql_query("SELECT `site_id` FROM `table` WHERE `user_id`='{$data->id}'");
$data = array();
while ($issues_row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$data[] = $issues_row['site_id'];
}
$result = implode(",", $data);
现在,如果我使用:
$nr = randWithout(500, 550, array($result));
它不起作用,所以我的问题是 array($result) 这里有什么问题?
【问题讨论】:
标签: php arrays exception random