0

我已经检查了很多关于循环的解决方案,但仍然不能适用于我的问题。尽管如此,仍然对循环感到困惑。我想生成随机数,然后检查生成的数字是否等于表列的内容,如果它相同,它将再次生成,直到它没有相同的值。

希望大家帮助我,所以我们开始吧。

我在数据库中有一个名为“list”的表,它的结构为idimg ,它包含的值为

清单表:

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

4

2 回答 2

3

使用do...while循环:

do {
    $rand = rand(1, 5);
} while (in_array($rand, $new_array));

虽然我不确定为什么需要生成这样的随机数。为什么需要这个号码?

于 2013-01-23T08:24:26.500 回答
0

在这种情况下,递归函数可能很有用。

  1. 内部函数创建一个随机字符串
  2. 在数据库中检查它
  3. 如果存在则再次移动调用递归函数
  4. 否则返回字符串
于 2013-01-23T09:08:39.657 回答