Infinitus classification output method and classification output method
Data:
$ Data = array (
Array (
'Id' => 1,
'Parent _ id' => 0,
'Name' => 'first'
),
Array (
'Id' => 2,
'Parent _ id' => 1,
'Name' => 'second'
),
Array (
'Id' => 3,
'Parent _ id' => 2,
'Name' => 'third'
),
Array (
'Id' => 4,
'Parent _ id' => 3,
'Name' => 'forth'
),
);
Call: $ res = $ this-> make_tree1 ($ data );
Encapsulation Method
Method 1: foreach Loop
// Method 1: The foreach loop achieves an infinitus
Public function make_tree ($ list, $ pk = 'id', $ pid = 'parent _ id', $ child = 'children ', $ root = 0)
{
$ Tree = array ();
$ Temp = array ();
Foreach ($ list as $ data)
{
$ Temp [$ data [$ pk] = $ data;
}
Foreach ($ temp as $ key => $ val)
{
If ($ val [$ pid] ==$ root)
{// Represents a node
$ Tree [] = & $ temp [$ key];
}
Else
{
// Find the parent class
$ Temp [$ val [$ pid] [$ child] [] = & $ temp [$ key];
}
}
Return $ tree;
}
// Method 2: Recursive Method for infinitus
Public function make_tree1 ($ list, $ pk = 'id', $ pid = 'parent _ id', $ child = 'children ', $ root = 0)
{
$ Tree = array ();
Foreach ($ list as $ key => $ val)
{
If ($ val [$ pid] ==$ root)
{
// Obtain all subclasses of the current $ pid
Unset ($ list [$ key]);
If (! Empty ($ list ))
{
$ Child = $ this-> make_tree1 ($ list, $ pk, $ pid, $ child, $ val [$ pk]);
If (! Empty ($ child ))
{
$ Val ['_ child'] = $ child;
}
}
$ Tree [] = $ val;
}
}
Return $ tree;
}