2015-04-26 71 views
0

我有一个迭代excel文件的每一行的foreach循环。随着我从单行检索的数据运行一些查询,选择或插入我的数据库中的一些数据。一个查询的 例子我运行:在foreach循环中继续使用

if($error == ''){ 
    try{ 
     $s2 = $pdo->prepare("SELECT anagrafiche.id_ndg FROM anagrafiche 
      WHERE anagrafiche.cod_fisc = '$cf_cedente' 
      OR anagrafiche.p_iva = '$cf_cedente' 
      OR anagrafiche.cf_estero = '$cf_cedente'"); 
     $s2->execute(); 
    } 
    catch (PDOException $e){ 
     $error = 'Errore nel trovare anagrafica cedente: '.$e->getMessage();  
     echo 'Non trovato cedente con codice fiscale '.$cf_cedente.' ';    
    }     
}    

这种情况结束了很多嵌套如果因为我不想当一个错误是在一个特定的点抛出一些查询运行。 如果我使用继续停止当前行来执行并跳转到下一个而不是这种情况,那么在执行时间或资源方面会更好吗?因此,代码将如下所示:

try{ 
    $s2 = $pdo->prepare("SELECT anagrafiche.id_ndg FROM anagrafiche 
     WHERE anagrafiche.cod_fisc = '$cf_cedente' OR anagrafiche.p_iva = 
     '$cf_cedente' OR anagrafiche.cf_estero = '$cf_cedente'"); 
    $s2->execute(); 
} 
catch (PDOException $e){ 
    $error = 'Errore nel trovare anagrafica cedente: '.$e->getMessage();  
    echo 'Non trovato cedente con codice fiscale '.$cf_cedente.' ';   
}     
if($error!=''){ 
    echo $error; 
    continue; 
} 

或者还有一个更好的选项,我还没有想过呢? 谢谢你的帮助! 注意:我正在执行大量数据加载,所以我需要继续加载下一行,跳过出错的那一行。

回答

1

引述PHP手册,

continue被循环结构内使用跳过 当前循环迭代的其余部分,并在条件 评价继续执行,然后下一个迭代的开始。

break结束当前对,的foreach的执行,而,做-而或 开关结构。

这两个关键字都接受一个可选的数字参数,告诉它应该跳过多少个嵌套的封闭结构跳到末尾/分出。

所以是的,如果一个错误只影响一行,使用continue;跳到下一行。如果单行中遇到的错误是致命的并且会影响所有行,请使用break;结束foreach循环。