Class: Tree

Handles managing a tree of objects as a JSON file. Items in the tree have the following structure:

{"data":"Title or name","attr":{"id":"ID value","sort":0}}

Item that have children will have an additional children property that is an array of other items.


$n = new Tree ('conf/categories.json');
// $n->tree contains data from conf/categories.json

$n->add ('Topics');
$n->add ('Design', 'Topics');
$n->add ('Web Design', 'Design');
$n->add ('Print Design', 'Design');
// etc.

$node = $n->node ('Web Design');
// {"data":"Web Design","attr":{"id":"Web Design","sort":0}}

$path = $n->path ('Web Design');
// array ('Topics', 'Design', 'Web Design')

$n->move ('Web Design', 'Design', 'before');
$ids = $n->get_all_ids ();
// array ('Topics', 'Web Design', 'Design', 'Print Design')

$n->remove ('Web Design');

// save out to conf/categories.json
$n->save ();


public $file

The file that contained the JSON tree structure.

public $tree = array ()

The tree structure.

public $error = false

The error message if an error occurs, or false if no errors.


public __construct ($file)

Constructor method. Decodes the tree from the specified file in JSON format.

public get_all_ids ($tree = false)

Get all page ids from the tree.

public sections ($tree = false)

Get the section nodes, meaning all nodes that have sub-nodes.

public node ($id, $tree = false)

Find a specific node in the tree.

public parent ($id, $tree = false)

Find the parent of a specific node in the tree.

public path ($id, $titles = false, $tree = false)

Find the path to a specific node in the tree, including the node itself. If titles is true, it will return an associative array with the keys being object IDs and the values being their data attribute (usually, the title or name). If $titles is false, it will return an array of IDs only.

public add ($obj, $parent = false, $data = false)

Add an object to the tree under the specified parent node. $id can be an ID or a node object. If $data is passed, it it will set the data property to that instead of the value of $obj, which would typically be used as follows:

$mytree->add ('id-value', 'parent-id', 'Title here');

public remove ($id, $recursive = true)

Remove an object from the tree. Removes all children as well unless you set $recursive to false.

public remove_path ($path)

Remove a specific path from the tree recursively. Used primarily by move().

public move ($id, $ref, $pos = 'inside')

Move an object to the specified location ($ref) in the tree. $pos can be one of: after, before, inside (default is inside).

public update ($tree)

Update the tree from Json to the file.

public save ()

Save the tree out to the file.