【发布时间】: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