【问题标题】:PHP exit inner foreach loop and carry on with outer loopPHP退出内部foreach循环并继续外部循环
【发布时间】:2016-01-09 17:00:33
【问题描述】:

我在 PHP 中的 foreach 循环有一些问题。

我有一个外部 foreach 循环和一个内部 foreach 循环。

循环的基础是,我有一些来自表单的发布数据,以及一些来自数据库的数据。外层循环遍历每个发布的数据,然后将其与数据库内层循环中的数据进行比较。

我遇到的问题是,在每个外循环中,如果在内循环上找到一个条目,外循环如何知道它已找到,然后不再重复该条目。

所以,这是我正在使用的代码,我已经发表了评论,以便您可以看到我在逻辑上遇到的问题

        // get posted data      
    foreach($posted_vals as $post_key => $post_value) {

        // query all data in assignments table      
        foreach($existing_ids as $db_key => $db_value) {

            // check if user_id($db_value) matches ($post_value), 
            // if not then post to db

            // if this loop does not find matching data and
            // posts to the database, how does the outer loop
            // know its been found and then not post again to database

        } 

        // any entries not found in db, post to db ... er but hang on,
        // how do i know if any entries were posted???

    } 

【问题讨论】:

  • 添加逻辑测试,如果测试为真则使用break
  • 如何测试一个值是否出现在两个关联数组中? if($posted_vals[user_id]==$existing_ids[user_id]) 。我似乎无法在内部循环之外进行比较??!?

标签: php mysql arrays loops foreach


【解决方案1】:

您可以设置一个标志变量isFound,无论帖子是否在内循环中找到。最初变量是false,但如果在内部循环中找到帖子,它将更新为true,然后在外部循环中,您可以检查isFound 是真还是假。因此,您可以检查您的帖子是否在内循环中找到。以下是你可以做到的:

// get posted data      
foreach($posted_vals as $post_key => $post_value) {
    $isFound = false;
    // query all data in assignments table      
    foreach($existing_ids as $db_key => $db_value) {
      //if found in db then set $isFound = true;
    } 
    //if(!isFound) that means if the post was not found
    // any entries not found in db, post to db ... er but hang on,
    // how do i know if any entries were posted???
} 

【讨论】:

    【解决方案2】:

    将 db-comparison 放在单独的函数中可能会更清楚:

    foreach($posted_vals as $post_key => $post_value) {
        if(compareWithDbValues($post_value)) {
            return true;
        }
    }
    
    function compareWithDbValues($post_value) {
        foreach($existing_ids as $db_key => $db_value) {
            if($db_value == §post_value) {
                return true;
            }
        }
    
        return false;
    }
    

    如果您没有在单独的函数中使用它,只需在内部 for 循环中使用 break 而不是 return true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      相关资源
      最近更新 更多