生成随机数,如果不是循环,则检查db列的值是否为相同值

时间:2013-01-23 08:20:23

标签: php

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

希望你们帮助我,所以我们走了。

我在数据库中有一个名为“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

2 个答案:

答案 0 :(得分:3)

使用do...while循环:

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

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

答案 1 :(得分:0)

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

  1. 内部函数创建一个随机字符串
  2. 在数据库中检查
  3. 如果存在,则再次移动呼叫递归功能
  4. else return string