douduikai0562 2015-04-26 17:55
浏览 881
已采纳

在foreach循环中使用continue

I have a foreach loop that iterates each row of an excel file. With the data I retrieve from the single row I run some query that select or insert some data in my db. Example of one query I run:

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.' ';             
    }                   
}               

This situation ends up with a lot of nested if because I don't want some query to run if an error is thrown at a specific point. Would it be better in terms of execution time or resources if I use continue to stop the current row to be executed and jump to the next instead of this situation? So that the code would look like:

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;
}

Or there is an even better option I haven't thought about yet? Thank you for your help! Note: I am doing a massive data load so I need continue to load the next row skipping the one that is in error.

  • 写回答

1条回答 默认 最新

  • doutangshuan6473 2015-04-26 18:08
    关注

    To quote the php manual,

    continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

    whereas

    break ends execution of the current for, foreach, while, do-while or switch structure.

    both keywords accept an optional numeric argument which tells it how many nested enclosing structures should skipped to the end of / broken out of.

    So yes, if an error only affects one row, use continue; to skip to the next row. If an error encountered in a single row is fatal and affects all rows, use break; to end the foreach loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题