PHP退出内部foreach循环并进行外循环

时间:2016-01-09 17:00:33

标签: php mysql arrays loops foreach

我在PHP中遇到了一些关于foreach循环的问题。

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

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

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

所以,这是我正在使用的代码,我已经评论过,所以你可以看到我在逻辑上遇到的问题

        // 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???

    } 

2 个答案:

答案 0 :(得分: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???
} 

答案 1 :(得分:1)

将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