PHP中的嵌套foreach循环导致在循环期间向数组追加重复项


nested foreach loop in php causing duplicates in items appended to array during loop

我在php论坛上多次问过这个问题,但是没有回应。基本上,我正在使用codeigniter和一个称为datamapper的对象关系映射器。在实例化对象时,它将数据库表存储为对象,并将字段存储为属性。我正试图比较两个对象的属性,以确定要删除哪些记录。基本上是这样的:

http://blog.jeremymartin.name/2008/02/easy-multi-select-transfer-with-jquery.html

我已经成功创建了添加函数。但现在我对编辑功能感到困惑。用户可能想要删除与某个类别关联的父类,或者向该类别添加新的父类。因此,我需要考虑到这一点,并相应地更新categores_related_categories连接表。

但是当我尝试在foreach循环中比较对象属性时,它会迭代内部循环两次并复制属性:

public function update(){
        $vanity_url = new VanityUrl();
        $vanity_url->where('user_id',$this->current_user()->id)->get();
        $zones = $this->input->post('zones');
        $zone = new Zone();
        $zone->where_in('name', $zones)->get();
        $subcategory = new Category();
        $subcategory->where('id',$this->uri->segment(4))->get();
        $old_parents = new Category();
        $old_parents = $subcategory->related_category->get();
        $unneeded_ids = array(); 
        if(!$this->input->post('catupload')){
            if($subcategory->save($zone->all)){
                redirect("blogs/$vanity_url->url/categories"); 
            }
            else {
                echo "Error occurred. Please try again.";
            }
        }
        else {
            $new_parents = new Category();
            $controller = $this->input->post('catupload');
            $new_parents->where_in('controller',$controller)->get();
            foreach($new_parents as $new){ 
                foreach($old_parents as $old){
                    if($new->id != $old->id){
                        array_push($unneeded_ids, $old->id);
                    }
                }
            }
            $subcategory->delete($subcategory->related_category->where_in('id',$unneeded_ids)->get());
if($subcategory->save(array($zone->all,$new_parents->all))){
                $this->session->set_flashdata('flash_message', 'The category has been successfully updated.');
                redirect("blogs/$vanity_url->url/categories");
            }
        }
    }

因此,我通过抓取与用户选择的内容不匹配的id并删除相关记录来删除用户不再需要的任何关系。

问题来了:

array(4) { [0]=> int(126) [1]=> int(127) [2]=> int(126) [3]=> int(127) } 

应该是这样的,因为id不能被复制:

 array(2) {[0]=> int(126) [1]=> int(127)}

感谢您的回复

如果你想在数组中存储唯一的元素,使用它作为关联映射:使用元素作为键。

也就是说,如果您想将元素$id(整数)存储在数组$arr中,而不是

array_push($arr, $id  );

:

$arr[$id] = $id  

$arr[$id] = 1; // or whatever
之后,您可能需要array_keys

我还没有测试过,但是你可以使用:

foreach($new_parents as $new){ 
    foreach($old_parents as $old){
        if($new->id != $old->id && !in_array($old->id, $unneeded_ids){
            array_push($unneeded_ids, $old->id);
        }
    }
}  

. .检查id是否已经在数组中列出?

http://php.net/manual/en/function.in-array.php