我已经检查了很多关于循环的解决方案,不能适用于我的问题。 但仍然对循环感到困惑。我想生成随机数然后检查,如果生成的数字等于表格列的内容,如果它与它再次生成的相同,直到它不再生成具有相同的价值。
希望你们帮助我,所以我们走了。
我在数据库中有一个名为“list”的表,它的结构为 id 和 img 它包含
的值列表:
id | img
1 | 1
2 | 2
3 | 3
4 | 4
number.php
$new_array = array();
$query = "SELECT img FROM list";
$query = mysql_query($query);
while ($query_get = mysql_fetch_array($query)) {
$new_array[] = $query_get[0]; //Store img values into an array
}
$rand = rand(1,5); //Generates random number 1 to 5
$search_r = array_search($rand, $new_array); //Checks if the random number has the same value to the array
while($search == "") { //Until random number gets number 5 it would stop looping
$rand = rand(1,5);
}
echo $rand; //and echo the number 5 here.
结果仍然是我的浏览器不间断加载屏幕
我有这段代码来确定随机数和数组是否具有相同的值。但它只在一个循环中表现良好。
if (array_search($rand,$new_array)) {
echo "random number has the same value inside the array" . $rand;
} else {
echo "random number does not have the same value inside an array" . $rand;
}
为简短起见,我的表 img中的值为1,2,3,4 ,而我生成数字1到5 。在生成的数字输出5之前,它将回显。如果生成的数字 1到4,它将再次生成,直到达到5 。
答案 0 :(得分:3)
使用do...while
循环:
do {
$rand = rand(1, 5);
} while (in_array($rand, $new_array));
虽然我不确定为什么你需要生成这样的随机数。你为什么需要这个号码?
答案 1 :(得分:0)
递归函数在这种情况下可能很有用。