This article mainly introduces the php tree type, which involves the tree structure in the data structure and algorithm. The instance is relatively simple and easy to understand. It has some reference value for learning the data structure. For more information, see
This article mainly introduces the php tree type, which involves the tree structure in the data structure and algorithm. The instance is relatively simple and easy to understand. It has some reference value for learning the data structure. For more information, see
This example describes the php tree type. Share it with you for your reference. The specific analysis is as follows:
The principle of this instance is simple. after learning the data structure, you can see what it means. However, when using the data, the subnode id (71) appears) less than the parent node id (104 ). as a result, the part of the node is not stored in the array. The instance code is modified as follows:
The Code is 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 PHP programming.
,