2011-09-28 58 views
1

当我执行此代码:问题决裂,而使用它打破嵌套循环在PHP

$result = mysql_query("SELECT * FROM example_table"); 

$i = 0; 
while ($row = mysql_fetch_array($result)) 
{ 
    for ($j = 0; $j < $c; $j++) 
    { 
     if ($db_array[$j]['ID'] == $row['id']) 
     { 
      $del_counter = 0; 
      break 2; 
     } 
     else 
     $del_counter = 1; 
    } 

    if ($del_counter == 1) 
    { 
    $del_array[$i] = $row['id']; 
    $i++; 
    } 

} 

这不破二级循环。相反,$ del_array存储所有的行标识符。我需要比较db_array [] [id]和数组“row”(从数据库中提取)。并且需要检查从数据库中删除了哪些db_array元素。所以,我所做的是我试图将已删除项目的ID存储在数组中。但休息不起作用。我错过了什么吗?

感谢您的期待。

BG

+0

尝试在嵌套for之前定义$ del_counter = 0。 –

+1

我不想听起来粗鲁,但“break 2”会按照公布的方式工作,所以我会认为你的代码中存在逻辑缺陷。使用分步调试器来查看你的代码在做什么。 – hakre

+0

你能重新说明一下吗?如果一行被删除,您希望如何检索它? – mowwwalker

回答

2

根据PHP手册:

1) break ends execution of the current for, foreach, while, do-while or switch structure 
2) break accepts an optional numeric argument which tells it 
how many (the above mentioned) nested enclosing structures are to be broken out of 

你休息是2级,因此break 2;应该按预期方式工作,所以这个问题是其他地方。 break 2是否执行?

无论如何,我会推荐一个更强大的解决方案,例如,

$ok = True; 
while (($row = mysql_fetch_array($result)) && $ok) { 
     ... 
     if (...) $ok = False; // anywhere deep 
     ... 
     if ($ok) {...} 
} 
+0

休息结束时,foreach,while,do-while或switch结构的当前执行,所以休息2将按预期工作 – matino

+0

@matino:你是对的,我编辑了我的答案。 – Jiri

+0

谢谢Jiri和matino。然而,第一次为我工作。在那一刻我无法弄清楚这是我身边的逻辑错误。 – BasicGem