[英]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.