带有MYSQL返回的双while循环 [英] Double while loop with MYSQL return

查看:86
本文介绍了带有MYSQL返回的双while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 中的 MySQL 双循环:

MySQL double while loop in php:

$geta=mysql_query("SELECT id FROM table1 WHERE id<50");
while($row=mysql_fetch_array($geta)){
while($row2=mysql_fetch_array($geta)){
$id1=$row['id'];
$id2=$row2['id'];
echo "$id1 and $id2";
}
}

我正在尝试将 id 与另一个 id 进行各种可能的组合.

I'm trying to make every possible combination of id with another id.

不确定它有什么问题...输出只是一个 id1 列表...

Not sure what is wrong with it...output is just a list of id1...

我在这里做错了什么?

推荐答案

每次调用 mysql_fetch_array() 时,都会从 MySQL 数据库的相同结果集中获取下一个结果.因此,在外循环和内循环中调用它两次只会使记录指针前进.

Each time you call mysql_fetch_array(), you fetch the next result from the same result set from the MySQL database. So calling it twice in an outer and inner loop just advances the record pointer.

在您的情况下,您应该首先将所有结果加载到单个数组中,然后对其进行迭代:

In your case, you should load all results to a single array first, then iterate over that:

// Array to hold all results
$results = array();
$geta = mysql_query("SELECT id FROM table1 WHERE id<50");
while($row = mysql_fetch_array($geta)){
  // Append all rows to the array
  $results[] = $row;
}

// Now iterate over your array $results in the outer & inner loops
foreach ($results as $r1) {
  foreach ($results as $r2) {
    echo "$r1  and $r2";
  }
}

这篇关于带有MYSQL返回的双while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆