createNode($nodeName); // add the root node to the tree $this->tree['rootNode'] = &$rootNode; } /** * Find a node that matches the given string. * * @param string $name * Name of the node we are searching for. * @param array (ref) $parentNode which parent node should we search in ? * * @return array(ref) | false node if found else false */ public function &findNode($name, &$parentNode) { // if no parent node specified, please start from root node if (!$parentNode) { $parentNode = &$this->tree['rootNode']; } // first check the nodename of subtree itself if ($parentNode['name'] == $name) { return $parentNode; } $falseRet = FALSE; // no children ? return false if ($this->isLeafNode($node)) { return $falseRet; } // search children of the subtree foreach ($parentNode['children'] as $key => $childNode) { $cNode = &$parentNode['children'][$key]; if ($node = &$this->findNode($name, $cNode)) { return $node; } } // name does not match subtree or any of the children, negative result return $falseRet; } /** * Check if node is a leaf node. * Currently leaf nodes are strings and non-leaf nodes are arrays * * @param array $node node which needs to checked * * @return bool */ public function isLeafNode(&$node) { return (count($node['children']) ? TRUE : FALSE); } /** * Create a node. * * @param string $name * * @return array * (ref) */ public function &createNode($name) { $node['name'] = $name; $node['children'] = array(); $node['data'] = array(); return $node; } /** * Add node. * * @param string $parentName * Name of the parent ?. * @param array (ref) $node - node to be added * * @return void */ public function addNode($parentName, &$node) { $temp = ''; $parentNode = &$this->findNode($parentName, $temp); $parentNode['children'][] = &$node; } /** * Add Data. * * @param string $parentName Name of the parent ?. * @param string $childName - key to be used (optional) * @param mixed $data - data to be added * * @return void */ public function addData($parentName, $childName, $data) { $temp = ''; if ($parentNode = &$this->findNode($parentName, $temp)) { foreach ($parentNode['children'] as $key => $childNode) { $cNode = &$parentNode['children'][$key]; if ($cNode = &$this->findNode($childName, $parentNode)) { $cNode['data']['fKey'] = &$data; } } } } /** * Get Tree. * * @return tree */ public function getTree() { return $this->tree; } /** * Print the tree. * * @return void */ public function display() { print_r($this->tree); } }