在php中使用break来中断嵌套循环时出现问题
当我执行此代码时:在php中使用break来中断嵌套循环时出现问题,php,arrays,break,Php,Arrays,Break,当我执行此代码时: $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;
$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++;
}
}
$result=mysql\u查询(“从示例表中选择*);
$i=0;
while($row=mysql\u fetch\u数组($result))
{
对于($j=0;$j<$c;$j++)
{
if($db_数组[$j]['ID']==$row['ID']))
{
$del_计数器=0;
破口2;
}
其他的
$del_计数器=1;
}
如果($del_计数器==1)
{
$del_数组[$i]=$row['id'];
$i++;
}
}
这不会打破两级循环。相反,$del_数组存储所有行ID。我需要将db_数组[][id]与数组“row”(从数据库中获取)进行比较。并且需要检查从数据库中删除了db_数组的哪些元素。因此,我所做的是尝试将已删除项目的ID存储在一个数组中。但这种休息并不起作用。我错过什么了吗
谢谢你的期待
BG根据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代码>应按预期工作,因此问题在别处。是否执行了中断2
在任何情况下,我都会推荐一个更健壮的解决方案,例如
$ok = True;
while (($row = mysql_fetch_array($result)) && $ok) {
...
if (...) $ok = False; // anywhere deep
...
if ($ok) {...}
}
尝试在嵌套的for之前定义$del_counter=0。我不想听起来很粗鲁,但是break 2
将按所宣布的那样工作,因此我假设您的代码中存在逻辑缺陷。使用step调试器查看您的代码在做什么。您能重新表述一下吗?如果删除了一行,您希望如何检索它?不是说您总是在else
?如果您说$del_数组包含整个结果,那么这意味着如果($db_数组[$j]['ID']==$row['ID'])没有正确定义,因为它从未设置为true。break结束当前for、foreach的执行,而,做一段时间或切换结构,使break 2按预期工作谢谢Jiri和matino。然而,break 1对我来说很有效。这是我这边的一个逻辑错误,我当时无法理解。