Author:askie blog:http://www.pkphp.com Copyright: Random use of unlimited classification
<?php
/**
* Author:askie
* blog:http://www.pkphp.com
* Copyright: Casual Use
* Infinite Classification
*/
Class Tree
{
Public $data =array ();
Public $cateArray =array ();
function tree ()
{
}
function Setnode ($id, $parent, $value)
{
$parent = $parent? $parent: 0;
$this->data[$id] = $value;
$this->catearray[$id] = $parent;
}
function Getchildstree ($id =0)
{
$childs =array ();
foreach ($this->catearray as $child => $parent)
{
if ($parent = = $id)
{
$childs [$child]= $this->getchildstree ($child);
}
}
return $childs;
}
function Getchilds ($id =0)
{
$childArray =array ();
$childs = $this->getchild ($id);
foreach ($childs as $child)
{
$childArray []= $child;
$childArray =array_merge ($childArray, $this->getchilds ($child));
}
return $childArray;
}
function Getchild ($id)
{
$childs =array ();
foreach ($this->catearray as $child => $parent)
{
if ($parent = = $id)
{
$childs [$child]= $child;
}
}
return $childs;
}
Single Line get parent node
function Getnodelever ($id)
{
$parents =array ();
if (key_exists ($this->catearray[$id], $this->catearray))
{
$parents []= $this->catearray[$id];
$parents =array_merge ($parents, $this->getnodelever ($this->catearray[$id]));
}
return $parents;
}
function Getlayer ($id, $preStr = '-')
{
Return Str_repeat ($PRESTR, Count ($this->getnodelever ($id));
}
function GetValue ($id)
{
return $this->data[$id];
}//End Func
}
$Tree = new Tree ("Please select category");
Setnode (directory ID, superior ID, directory name);
$Tree->setnode (1, 0, ' directory 1′);
$Tree->setnode (2, 1, ' directory 2′);
$Tree->setnode (5, 3, ' directory 5′);
$Tree->setnode (3, 0, ' directory 3′);
$Tree->setnode (4, 2, ' directory 4′);
$Tree->setnode (9, 4, ' directory 9′);
$Tree->setnode (6, 2, ' directory 6′);
$Tree->setnode (7, 2, ' directory 7′);
$Tree->setnode (8, 3, ' directory 8′);
Print_r ($Tree->getchildstree (0));
Print_r ($Tree->getchild (0));
Print_r ($Tree->getlayer (2));
$category = $Tree->getchilds ();
Traverse output
foreach ($category as $key => $id)
{
echo $id. $Tree->getlayer ($id, '-'). $Tree->getvalue ($id). " \ n ";
}
?>