This example describes the PHP tree class. Share to everyone for your reference. The specific analysis is as follows:
This example principle is simple, has studied the data structure a look to understand is what rationale, but today in use data appears the child Node ID (71) is less than the parent node ID (104). Cause some of the child nodes are not stored in the array, modified, the instance code is as follows:
Copy Code code as follows:
<?php
Class Tree
{
var $data = array ();
var $child = array ( -1=>array ());
var $layer = array ( -1=>-1);
var $parent = array ();
var $num = array ();
function Setnode ($id, $parent, $value, $num =0)
{
$parent = $parent? $parent: 0;
$this->data[$id] = $value;
$this->num[$id] = $num;
if (!isset ($this->child[$id)) $this->child[$id] = array ();
$this->child[$parent] = $id;
$this->parent[$id] = $parent;
if (!isset ($this->layer[$parent]) && $parent = 0)
{
$this->layer[$id] = 0;
}
Else
{
$this->layer[$id] = $this->layer[$parent] + 1;
}
}
Function GetList (& $tree, $root = 0)
{
foreach ($this->child[$root] as $key => $id)
{
$tree [] = $id;
if ($this->child[$id]) $this->getlist ($tree, $id);
}
}
function GetValue ($id)
{
if ($this->layer[$id]==0)
{
return $this->data[$id];
}
Else
{
Return $leftmar. $this->data[$id];
}
}
function Getnum ($id)
{
return $this->num[$id];
}
function Getbitvalue ($id)
{
return $this->data[$id];
}
function Getlayer ($id, $space = False)
{
Return $space? Str_repeat ($space, $this->layer[$id]): $this->layer[$id];
}
function GetParent ($id)
{
return $this->parent[$id];
}
function Getparents ($id)
{
while ($this->parent[$id]!=-1)
{
$id = $parent [$this->layer[$id]] = $this->parent[$id];
}
Ksort ($parent);
Reset ($parent);
return $parent;
}
function Getchild ($id)
{
return $this->child[$id];
}
function Getchilds ($id = 0)
{
$child = Array ($id);
$this->getlist ($child, $id);
return $child;
}
function Printdata ()
{
return $this->layer;
}
}
?>
I hope this article will help you with your PHP program design.