我已经检查了很多关于循环的解决方案,但仍然不能适用于我的问题。尽管如此,仍然对循环感到困惑。我想生成随机数,然后检查生成的数字是否等于表列的内容,如果它相同,它将再次生成,直到它没有相同的值。
希望大家帮助我,所以我们开始吧。
我在数据库中有一个名为“list”的表,它的结构为id和img ,它包含的值为
清单表:
id | img
1 | 1
2 | 2
3 | 3
4 | 4
数字.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 之前,它会 echo。如果生成的数字得到1 到 4 ,它将再次生成,直到得到 5。