2012-06-23 73 views
2

我测试循环嵌套工作时语句,以便:PHP嵌套While循环不mysql_fetch_assoc

$count1 = 0; 

while ($count1 < 3) { 
$count1++; 
$count2 = 0; 
echo "count1: ".$count1."<br />"; 

    while ($count2 < 3) { 
    $count2++; 
    echo "count2: ".$count2."<br />"; 
    } 
} 

这工作完全与结果(循环各三次):

count1: 1 
count2: 1 
count2: 2 
count2: 3 
count1: 2 
count2: 1 
count2: 2 
count2: 3 
count1: 3 
count2: 1 
count2: 2 
count2: 3 

然后我试图同使用mysql_fetch_assoc($ ContactsInterests是两行关联数组,并且$ LatestNeNe具有50行)的循环,即

$CI_count = 0; 

while ($CI_Row = mysql_fetch_assoc($ContactsInterests)) { //loop thru interests 
$CI_count++; 
$LN_count = 0; 
echo "CI_count: ".$CI_count."<br />"; 

while ($LN_Row = mysql_fetch_assoc($LatestNews)) { //loop thru news 
    $LN_count++; 
    echo "LN_count: ".$LN_count."<br />"; 

} 
} 

的结果是:

CI_count: 1 
LN_count: 1 
LN_count: 2 
... 
LN_count: 50 
LN_count: 51 
CI_count: 2 

但它LN_count的第二次迭代?我不明白为什么LN_count没有第二次增加。

帮助赞赏。

+1

mysql_data_seek($ result,0) – goat

+0

顶部添加$ LN_Row = array(); 然后,在第一个while循环结束时添加重置($ LN_Row); – arijeet

+0

@ redskins80'$ LN_Row'只包含由'mysql_fetch_assoc'传递的最后一个值......所以它不会填充'$ LN_Row',除非你像这样做'$ LN_Row [] = mysql_fetch_assoc' –

回答

3

mysql_fetch_assoc做迭代 “的MySQL结果” 类型。寻找每个抓取的索引。 您必须使用mysql_data_seek才能找到第一个结果;

<?php 

    $CI_count = 0; 

    while ($CI_Row = mysql_fetch_assoc($ContactsInterests)) { //loop thru interests 
     $CI_count++; 
     $LN_count = 0; 
     echo "CI_count: ".$CI_count."<br />"; 

     mysql_data_seek($LatestNews,0); 
     while ($LN_Row = mysql_fetch_assoc($LatestNews)) { //loop thru news 
      $LN_count++; 
      echo "LN_count: ".$LN_count."<br />"; 

     } 
    } 
+0

太棒了!感谢Tufan。奇迹般有效。 – Jeremy

0

因为结果已经用尽。你已经遍历所有这些...如果你想再次循环,你必须重新填充$ LatestNews变量。

0

mysql_fetch_assoc()一个接一个地取出源的行,当你在第一个循环的第二步时,你不会在源变量中有任何行。

您需要将第二个查询的结果放在数组中,然后循环数组,而不是使用mysql_fetch_assoc。