PHP嵌套while循环无法与mysql_fetch_assoc一起使用

4

我测试了嵌套While语句的循环:

$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 是一个两行的关联数组,$LatestNews 有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 没有第二次递增。
感谢您的帮助。

在顶部添加 $LN_Row = array(); 然后,在第一个 while 循环的末尾添加 reset($LN_Row); - arijeet
@redskins80,$LN_Row 只包含 mysql_fetch_assoc 传递的最后一个值... 因此,除非您执行类似 $LN_Row[] = mysql_fetch_assoc 的操作,否则它不会填充 $LN_Row - Dexter Huinda
@Dexter,你说得对!我已经删除了我的回答。抱歉。 - arijeet
1
立即停止使用 mySQL_* 扩展。它们已被弃用。请改用 PDO 或 I 扩展。 - Brendan Lesniak
不用担心,伙计们,@Jeremy现在可能正在睡觉,他没有回应。 - Dexter Huinda
4个回答

5

mysql_fetch_assoc用于迭代“mysql result”类型。每次获取数据时都会寻找索引。 您必须使用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

因为结果已经用尽了。您已经遍历了所有结果... 如果您想再次循环,您需要重新填充$LatestNews变量。


0

mysql_fetch_assoc() 会逐行获取源数据,当你在第一次循环的第二步时,源变量中将没有任何行。

你需要将第二个查询的结果放入一个数组中,然后循环该数组,而不是使用 mysql_fetch_assoc


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接