Zend Certified Engineer

phpguru.org

Free PHP, Javascript and C# code

Tree class

A class for handling tree strutures. Documentation available via inline docs and also in standalone Word and PDF formats. This is bundled using the PEAR installer, so you can download and install manually, or with the installer. It WILL conflict with the Tree class available via the PEAR website if you have it installed, so don't install both at once. Trust me, this is better. ;-)

Latest version

Latest version (2.0.0) is PHP5 only. Prior version is still available in the download area (1.0.3) for PHP4. Now totally takes advantage of PHP5s OO model and references. Also, creating a Tree structure is now facilitated by the Tree::factory() method, which takes a Tree_Factory_Iterator interface as an argument. Pass it an object and as long as it implements this interface (which incidentally inherits from RecursiveIterator) properly, then the factory method will return you a nice shiny new Tree object. Two examples are included which create Tree objects from an array (ala previous versions) and from the filesystem.

Some sample code:

<?php
    
require_once("Tree.php");
    require_once(
"Tree/Factory/FileSystem.php");
    
    
/**
    * Create a structure from a filesystem path.
    * Recurses down through directories
    */
    
$rit = new Tree_Factory_FileSystem(".");
    
    
$tree    = Tree::factory($rit);
    
$results = $tree->nodes->search("List.php");
?>

And this is the documentation from the head of Tree.php (which I couldn't be arsed to rewrite:

<?php
/**
* An OO tree class based on various things, including the MS treeview
* control.
*
* Structure of one of these trees:
*
*  Tree Object
*    |
*    +- Tree_NodeCollection object (public nodes property)
*          |
*          +- Array of Tree_Node objects (private nodes property)
*
* Usage:
*   $tree = new Tree();
*   $node  = $tree->nodes->add(new Tree_Node("1"));
*   $node2 = $tree->nodes->add(new Tree_Node("2"));
*   $node3 = $tree->nodes->add(new Tree_Node("3"));
*   $node4 = $node3->nodes->add(new Tree_Node("3_1"));
*   $tree->nodes->removeNodeAt(0);
*   print_r($tree);
*
* The data for a node is supplied by giving it as the argument to the
* Tree_Node constructor. You can retreive the data by using a nodes
* getTag() method, and alter it using the setTag() method.
*/
?>

Download now
Docs: Word :: PDF :: HTML

Link to me

If you use any of the code on this site (and if you don't I guess) or it makes your life easier, I'd appreciate a link - http://www.phpguru.org. Thanks.

Last modified: 17:05 29th December 2006