This article mainly introduces the example of PHP that does not require recursion to implement unlimited classification. it is actually a way of thinking and explained with a simple example, for more information, see the following two tree array operators that do not require recursion.
The code is as follows:
/**
* Create a parent node tree array
* Parameters
* $ Ar array, data organized in the form of an adjacent list
* $ Subscripts or associated key names used as primary keys in the id array
* $ Subscript or associated key name of the parent key in the pid array
* Returns a multi-dimensional array.
**/
Function find_parent ($ ar, $ id = 'id', $ pid = 'pid '){
Foreach ($ ar as $ v) $ t [$ v [$ id] = $ v;
Foreach ($ t as $ k => $ item ){
If ($ item [$ pid]) {
If (! Isset ($ t [$ item [$ pid] ['parent'] [$ item [$ pid])
$ T [$ item [$ id] ['parent'] [$ item [$ pid] = & $ t [$ item [$ pid];
}
}
Return $ t;
}
/**
* Create a subnode tree array
* Parameters
* $ Ar array, data organized in the form of an adjacent list
* $ Subscripts or associated key names used as primary keys in the id array
* $ Subscript or associated key name of the parent key in the pid array
* Returns a multi-dimensional array.
**/
Function find_child ($ ar, $ id = 'id', $ pid = 'pid '){
Foreach ($ ar as $ v) $ t [$ v [$ id] = $ v;
Foreach ($ t as $ k => $ item ){
If ($ item [$ pid]) {
$ T [$ item [$ pid] ['child '] [$ item [$ id] = & $ t [$ k];
}
}
Return $ t;
}
Example:
The code is as follows:
$ Data = array (
Array ('id' => 1, 'parent' => 0, 'name' => 'grandpa '),
Array ('id' => 2, 'parent' => 1, 'name' => 'father '),
Array ('id' => 3, 'parent' => 1, 'name' => 'Uncle '),
Array ('id' => 4, 'parent' => 2, 'name' => 'your '),
Array ('id' => 5, 'parent' => 4, 'name' => 'son '),
);
$ P = find_parent ($ data, 'id', 'parent ');
$ C = find_child ($ data, 'id', 'parent ');
Execution result:
The code is as follows:
Array
(
[1] => Array
(
[ID] => 1
[PARENT] => 0
[NAME] => grandfather
[Child] => Array
(
[2] => Array
(
[ID] => 2
[PARENT] => 1
[NAME] => father
[Child] => Array
(
[4] => Array
(
[ID] => 4
[PARENT] => 2
[NAME] => yourself
[Child] => Array
(
[5] => Array
(
[ID] => 5
[PARENT] => 4
[NAME] => son
)
)
)
)
)
[3] => Array
(
[ID] => 3
[PARENT] => 1
[NAME] => Uncle
)
)
)
[2] => Array
(
[ID] => 2
[PARENT] => 1
[NAME] => father
[Child] => Array
(
[4] => Array
(
[ID] => 4
[PARENT] => 2
[NAME] => yourself
[Child] => Array
(
[5] => Array
(
[ID] => 5
[PARENT] => 4
[NAME] => son
)
)
)
)
)
[3] => Array
(
[ID] => 3
[PARENT] => 1
[NAME] => Uncle
)
[4] => Array
(
[ID] => 4
[PARENT] => 2
[NAME] => yourself
[Child] => Array
(
[5] => Array
(
[ID] => 5
[PARENT] => 4
[NAME] => son
)
)
)
[5] => Array
(
[ID] => 5
[PARENT] => 4
[NAME] => son
)
)