[英]php - while loop is itering double the times expected and nested for loop is iterating 1.5 times more than expected
[英]PHP double while loop, second loop not iterating more than once
所以我正在开发一个“产品列表”,其想法是获得产品的名称,然后是从数据库派生的颜色下拉列表。 问题是我只能得到“颜色”而循环迭代一次,我得到第一个产品名称和下拉菜单中的颜色一次但不是随后,我想要的帮助,我怎么能改变这段代码让它做我需要的,我已经尝试了一个星期,我真的可以使用一些帮助。
$product_query = mysql_query('SELECT * FROM products WHERE id > 0');
$colour_query = mysql_query('SELECT * FROM product_colours WHERE id > 0');
while ($get_product_rows = mysql_fetch_assoc($product_query)){
echo $get_product_rows['name'];
echo "<br \>";
if ($get_product_rows['has_colour'] == '1'){
while ($get_colour_row = mysql_fetch_assoc($colour_query)){
// Drop down box population goes here.
}
}
}
如果有人可以提供帮助,我会很感激。 来自Grant M.
mysql_fetch_assoc()
工作方式是它有一个内部指针,每次运行该方法时,都会得到下一个项目并且指针被移动一次。 如果没有指针,那么while循环将如何终止? 它会一遍又一遍地拉出颜色。
解决此问题的方法是重置每次迭代中的点。 这可以使用mysql_data_seek()
。
$product_query = mysql_query('SELECT * FROM products WHERE id > 0');
$colour_query = mysql_query('SELECT * FROM product_colours WHERE id > 0');
while ($get_product_rows = mysql_fetch_assoc($product_query)) {
echo $get_product_rows['name'];
echo "<br />";
if ($get_product_rows['has_colour'] == '1') {
while ($get_colour_row = mysql_fetch_assoc($colour_query)) {
// Drop down box population goes here.
}
}
mysql_data_seek($colour_query, 0);
}
@Kristian Antonsen是非常正确的 - 一旦你在'结束'时读过行,除非你回到结果集的开头。
除了发布的其他答案之外,因为颜色不依赖于产品 - 获取它们一次然后在内存中重复使用它们。
// get the colours once
$colour_query = mysql_query('SELECT * FROM product_colours WHERE id > 0');
$colours = array();
while ($get_colour_row = mysql_fetch_assoc($colour_query)) {
array_push($colours, $get_colour_row['colour']);
}
// loop through each product
$product_query = mysql_query('SELECT * FROM products WHERE id > 0');
while ($get_product_rows = mysql_fetch_assoc($product_query)) {
echo $get_product_rows['name'];
echo "<br />\n";
if ($get_product_rows['has_colour'] == '1'){
foreach ($colours as $colour) {
echo $colour . "<br />\n";
}
}
}
问题是第二次,指针已经在$colour_query
记录的$colour_query
; 它将继续返回null
因为它不知道嵌套循环是否完整。
您可以通过使用mysql_data_seek
重置指针来解决此问题:
$product_query = mysql_query('SELECT * FROM products WHERE id > 0');
$colour_query = mysql_query('SELECT * FROM product_colours WHERE id > 0');
while ($get_product_rows = mysql_fetch_assoc($product_query)) {
echo $get_product_rows['name'];
echo "<br />";
if ($get_product_rows['has_colour'] == '1') {
while ($get_colour_row = mysql_fetch_assoc($colour_query)) {
// Drop down box population goes here.
}
// Reset the pointer:
mysql_data_seek($colour_query, 0);
}
}
而且,你的<br \\>
错了; 它应该是<br />
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.