php - Copy tree structure recursive - Adjacency List Model -
i try copy tree structure 1 database table another. structure adjacency list model. looks like:
id|parent_id|position 1|0|1 2|1|1 3|1|2 4|0|2 5|4|1
it necessary id's regenerated (autoinc) in other table! have following functions:
/** * copy single node , return new id */ public function copynode($sn_data){ $this->db2->insert('items_configurations', $sn_data); return $this->db2->insert_id(); } /** * return list of child nodes assoziative array * given parent */ public function childlist($parent_id){ $tmp = 'select parent_id,item_id,template_id,position items_templates parent_id='.$parent_id; $tmp .= ' order position'; $query=$this->db2->query($tmp); return $query->result_array(); } /** * copy whole tree structure through 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 $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 function example: */ $this->copytree(array('parent_id' => 0,'item_id' => 40,'template_id' => 6,'position' => 1),0);
i want recursive, copies first 2 lines. mistake?
1.you must use current node id
parent_id when traversing recursively. , using it's parent_id in childlist
:
parent_id='.$parent_id;
must parent_id='.$id;
you getting peers of node rather, it's children.
2.also suspicious marked line:
if(is_array($new_data)){ foreach($new_data $new_node_data) : $new_node_data['parent_id'] = $new_parent;//<-- $this->copytree($new_node_data); endforeach; }
because have new parent_id , using old table in childlist function. check, whether parameter correct.
Comments
Post a Comment