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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应