How to iterate through objects with undetermined nesting

1

I have a class named Document . Each Document can be the child of a Document or parent of a Document . Each Document can only have one parent and can have countless children.

I'm trying to write a Document->parentLevel() function to find out how many hierarchy levels (maximum) exist beneath this Document .

For example:

                     Doc1 
       Doc2          Doc3         Doc4
   Doc5    Doc 6
Doc7

When running Doc1->parentlevel() the function would return 3, because the highest number of hierarchical levels below it is 3 ( Doc2->Doc5->Doc7 ).

Objects have a function Document->hasChildren() that returns true or false if the object has children and a Document->children() function that returns a array with the children of that object.

My code so far:

public function parentLevel($startLevel = 0)
    {
        $level = $startLevel;
        $active = $this;
        while ($active->hasChildren()) {
            $level++;
            foreach ($children as $child) {
                if ($child->hasChildren()) {
                    $level2 = $child->parentLevel();
                    if ($level2 > $level) {
                        $level = $level2;
                    }
                }
            }
        }
        return $level;
    }
    
asked by anonymous 22.06.2017 / 23:44

1 answer

2

If you do not need to know which nodes are part of the larger branch, just do:

public function parentLevel ()
{
    $level = 0;

    if ($this->hasChildren())
    {
        $childrenLevels = [];

        foreach($this->children() as $child)
        {
            $childrenLevels[] = $child->parentLevel();
        }

        $level = max($childrenLevels) + 1;
    }

    return $level;
}
  

See working at Ideone .

Basically, if the node has children, look for the child that has the highest value of parentLevel and increments by 1, otherwise it returns 0.

    
23.06.2017 / 00:56