我尝试将树结构从一个数据库表复制到另一个。该结构是邻接列表模型。看起来像:
id|parent_id|position
1|0|1
2|1|1
3|1|2
4|0|2
5|4|1
有必要在另一个表中重新生成 (autoinc) id!我有以下功能:
/**
* 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);
我想做递归,但它只复制前两行。错误在哪里?