为什么不阻止进一步循环?

时间:2011-11-29 15:29:51

标签: php

我的代码在6次和2次迭代后似乎没有停止 - 为什么会这样?我不希望从服务中显示超过6个值,从文化中显示2个值。

ECHO "<fieldset>Services: ";
$servicearray = mysql_query("select serv_id from org_serv_xref where org_id='".$org_id."'");
while ($servicearrayrow = mysql_fetch_array($servicearray)) {
    $servdescarray = mysql_query("select serv_desc from service where serv_id='".$servicearrayrow['serv_id']."'");
    $i = 0;
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
        if ($i < 6) {
            ECHO $servdescarrayrow['serv_desc']." ";
            $i++;
        }
        else {
            break;
        }
    }
}
ECHO "</fieldset>";
ECHO "<fieldset>Cultures: ";
$culturearray = mysql_query("select cult_id from org_cult_xref where org_id='".$org_id."'");
while ($culturearrayrow = mysql_fetch_array($culturearray)) {
    $cultdescarray = mysql_query("select cult_desc from culture where cult_id='".$culturearrayrow['cult_id']."'");
    $i = 0;
    while ($cultdescarrayrow = mysql_fetch_array($cultdescarray)) {
        if ($i < 2) {
            ECHO $cultdescarrayrow['cult_desc']." ";
            $i++;
        }
        else {
            break;
        }
    }
}
ECHO "</fieldset>";

2 个答案:

答案 0 :(得分:2)

使用break 2代替breakbreak 2退出2级循环。

查看doc

您也可以在sql语句中使用LIMIT 6

答案 1 :(得分:0)

你在循环内外一遍又一遍 REDECLARING 相同的变量,这会让事情变得混乱:

while ($servicearrayrow = mysql_fetch_array($servicearray)) {
    $servdescarray = mysql_query("select serv_desc from service where serv_id='".$servicearrayrow['serv_id']."'");

    $i = 0;
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) { //<<WHA??