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;
}