I've written this in JavaScript but now need it in PHP, the logic looks OK but the recursive function fails to call itself.
thanks
Andy
= CODE ====================================
<?php
/**
This is the main tree object.
*/
class DataTree {
var $label;
var $level;
var $children; // array
/**
Constructor
*/
function DataTree ($aLabel, $aLevel) {
$this->label = $aLabel;
$this->level = $aLevel;
}
/**
*/
function addChild ($aNewChild) {
$this->children[] = $aNewChild;
}
/**
Initial function to start the recursion from the top node.
*/
function toHTML () {
$ls_HTML = $this->label."<br>";
$ls_HTML .= $this->getNextLevel($this);
// Finally return the HTML to be displayed.
return $ls_HTML;
}
/**
Recursive function called by each Node to display all of its children.
*/
function getNextLevel ($aNode) {
$ls_show = "";
$childCount = count(@$aNode->children);
for ($j=0; $j < $childCount; $j++) {
$child = $aNode->children[$j];
$ls_show .= str_pad('', ($child->level*4), ' +--');
$ls_show .= $child->label."<br>";
// Here's the tricky bit. Take each child of the node and call this function again.
$ls_show .= $aNode->getNextLevel($child);
};
return $ls_show;
}
}
/////////////////////////////////////////////////////////////////////
/**
Build the HTML
*/
echo "<BODY>";
$pr = new DataTree ('Root', 0);
$aaa = new DataTree ('AAA', 1);
$bbb = new DataTree ('BBB', 1);
$ccc = new DataTree ('CCC', 1);
$a1 = new DataTree ('A1', 2);
$b1 = new DataTree ('B1', 2);
$c1 = new DataTree ('C1', 2);
$pr->addChild($aaa);
$pr->addChild($bbb);
$pr->addChild($ccc);
$aaa->addChild($a1);
$bbb->addChild($b1);
$ccc->addChild($c1);
echo $pr->toHTML();
echo "</BODY>";
?>