【问题标题】:Copy tree structure recursive - Adjacency List Model递归复制树结构 - 邻接表模型
【发布时间】:2013-05-21 20:44:25
【问题描述】:

我尝试将树结构从一个数据库表复制到另一个。该结构是一个邻接列表模型。它看起来像:

id|parent_id|position
1|0|1
2|1|1
3|1|2
4|0|2
5|4|1 

必须在另一个表中重新生成 id(autoinc)!我有以下功能:

/**
 * Copy a single node and return the new id
 */
public function copyNode($sn_data){
    $this->db2->insert('items_configurations', $sn_data);
    return $this->db2->insert_id();
}

/**
 * Return a list of child nodes as an assoziative array
 * from a given parent
 */
public function childList($parent_id){
    $tmp  = 'SELECT parent_id,item_id,template_id,position FROM items_templates WHERE parent_id='.$parent_id;
    $tmp .= ' ORDER BY position';
    $query=$this->db2->query($tmp);
    return $query->result_array();
}

/**
 * Copy the whole tree structure through an recursive function
 */
public function copyTree($node_data,$given_parent){
    $new_parent = $this->copyNode($node_data);
    $new_data   = $this->childList($node_data['id']);
    if(is_array($new_data)){
        foreach($new_data as $new_node_data) :
            $new_node_data['parent_id'] = $given_parent;
            $new_node_data['configuration_id'] = $node_data['configuration_id'];
            $this->copyTree($new_node_data,$new_parent);
        endforeach;
    }
}


/**
 * First call of the function for example:
 */    
$this->copyTree(array('parent_id' => 0,'item_id' => 40,'template_id' => 6,'position' => 1),0);

我想递归,但它只复制前两行。哪里错了?

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    1.递归遍历时必须使用当前节点id作为parent_id。而你在childList中使用它的parent_id:

    parent_id='.$parent_id;
    

    必须是 parent_id='.$id;

    你得到的是这个节点的对等节点,然后是子节点。

    2.另外我对标记的线表示怀疑:

    if(is_array($new_data)){
        foreach($new_data as $new_node_data) :
            $new_node_data['parent_id'] = $new_parent;//<--
            $this->copyTree($new_node_data);
        endforeach;
    }
    

    因为您有一个新的 parent_id,然后将它与 childList 函数中的旧表一起使用。检查参数是否正确。

    【讨论】:

    • 嗨,首先谢谢。如果我像你这样告诉我复制了 id !这是不正确的,也是我的主要问题。我必须将表 1 中的树结构复制到表 2,但表 2 中的 id 是由 autoinc 生成的!例如,如果我想复制一棵树两次或在表 2 中更改它。
    • @grolle 将新的 parent_id 作为单独的参数传递并在 copyNode 函数中使用它
    • 嗨,谢谢,我已经编辑了我的第一篇文章,但它不起作用?!另一件事是如何处理第一级项目(parent_id=0)?
    • 您从 1 级项目开始,然后复制每个项目和它的子项目。不幸的是,我很难说,为什么你的代码不能在不能调试的情况下工作。尝试打印关键变量并检查它们的值。
    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多