Part of the EllisLab Network
   
 
MPTT recursive search and replace problem
Posted: 02 July 2009 08:18 AM   [ Ignore ]  
Grad Student
Rank
Total Posts:  34
Joined  08-15-2008

Hi all,

I’m trying to do a recursive search and replace on an MPTT tree.

The code I’m using is as follows

function parse($nodes) {
        
foreach($nodes as &$node) {
            
// Replace node?
            
if($node['type'] == 'ReferenceNode') {
                $n
= $this->site->get_node_where('id', $node['node_ref']);
                
// Replace node with node pointed to by reference
                
if($n) {
                    $node
= $this->site->get_node_where('object_id', $n['object_id']);
                    
// Get children
                    
$children = $this->site->get_descendants($node['lft'], $node['rgt']);
                    if(!empty(
$children)) {
                        $node[
'children'] = $this->parse($children);
                    
}
                }
            }
        }
        
return $nodes;
    
}

Basically the code hangs when I run it, although it looks like it should work. If I comment out

$node['children'] = $this->parse($children);

The code works fine, but obviously doesn’t deal with child nodes.

Cheers,
Gaz.

Profile
 
 
Posted: 04 July 2009 04:50 AM   [ Ignore ]   [ # 1 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  740
Joined  08-03-2006

Are you sure you won’t get any “circular references” with the database keys?
(Eg. node.node_ref -> n, n.object_id -> parent_node, parent_node.descendants ∈ node Makes everything repeat itself).

Also, the get_descendants() return *all* descendants, not only children, which means that your code also iterates grandchildren which already were replaced by a recursive call to this method. Try with get_children() instead.

Another thing may be the fact that if you move nodes in the tree, you can move some nodes which already have been moved (which also can result in an endless loop).

 Signature 

RapidDataMapper: My new ORM, is now released!

IgnitedRecord: Old ORM

MPTtree: A model to handle trees in a database.

YAYParser - Yet Another YAML Parser

Profile
 
 
Posted: 14 July 2009 10:16 AM   [ Ignore ]   [ # 2 ]  
Grad Student
Rank
Total Posts:  34
Joined  08-15-2008

You were right. There we’re circular references causing an infinite loop. D’oh!

Thanks for you help.

Cheers,
Gaz.

Profile
 
 
   
 
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 819, on March 11, 2010 11:15 AM
Total Registered Members: 120133 Total Logged-in Users: 36
Total Topics: 126279 Total Anonymous Users: 0
Total Replies: 664139 Total Guests: 330
Total Posts: 790418    
Members ( View Memberlist )