Two tree-shaped array manipulation functions without recursion
Copy the Code code as follows:
/**
* Create parent Node tree array
* Parameters
* $ar arrays, adjacency list-organized data
* $id the subscript or association key name in the array as the primary key
* $pid the subscript or association key name in the array as the parent key
* Returns a multidimensional 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 sub-node tree array
* Parameters
* $ar arrays, adjacency list-organized data
* $id the subscript or association key name in the array as the primary key
* $pid the subscript or association key name in the array as the parent key
* Returns a multidimensional 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;
}
Examples of Use:
Copy the Code code as follows:
$data = Array (
Array (' ID ' =>1, ' PARENT ' =>0, ' NAME ' = ' grandfather '),
Array (' ID ' =>2, ' parent ' =>1, ' NAME ' = ' father '),
Array (' ID ' =>3, ' PARENT ' =>1, ' NAME ' = ' uncles '),
Array (' ID ' =>4, ' PARENT ' =>2, ' NAME ' = ' own '),
Array (' ID ' =>5, ' PARENT ' =>4, ' NAME ' = ' son '),
);
$p = Find_parent ($data, ' ID ', ' parent ');
$c = Find_child ($data, ' ID ', ' PARENT ');
Execution effect:
Copy CodeThe 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] = = Himself
[Child] = = Array
(
[5] = = Array
(
[ID] = 5
[PARENT] = 4
[NAME] = son
)
)
)
)
)
[3] = = Array
(
[ID] = 3
[PARENT] = 1
[NAME] = uncles
)
)
)
[2] = = Array
(
[ID] = 2
[PARENT] = 1
[NAME] = Father
[Child] = = Array
(
[4] = = Array
(
[ID] = 4
[PARENT] = 2
[NAME] = = Himself
[Child] = = Array
(
[5] = = Array
(
[ID] = 5
[PARENT] = 4
[NAME] = son
)
)
)
)
)
[3] = = Array
(
[ID] = 3
[PARENT] = 1
[NAME] = uncles
)
[4] = = Array
(
[ID] = 4
[PARENT] = 2
[NAME] = = Himself
[Child] = = Array
(
[5] = = Array
(
[ID] = 5
[PARENT] = 4
[NAME] = son
)
)
)
[5] = = Array
(
[ID] = 5
[PARENT] = 4
[NAME] = son
)
)