Two tree array operation functions without recursion
Copy code The code is as follows:
/**
* Create a parent node tree array
* Parameters
* $ar array, data organized in adjacency list
* $id The subscript or associated key name as the primary key in the array
* $pid The subscript or associated key name as the parent key in the 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 tree array of child nodes
* Parameters
* $ar array, data organized in adjacency list
* $id The subscript or associated key name as the primary key in the array
* $pid The subscript or associated key name as the parent key in the 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;
}
Usage example:
Copy code
The code is as follows:$data = array(
array('ID'=>1, 'PARENT'=>0, 'NAME'=>'grandfather'),
array('ID'=>2, 'PARENT'=>1, 'NAME'=>'father') ,
array('ID'=>3, 'PARENT'=>1, 'NAME'=>'Uncle'),
array('ID'=>4, 'PARENT'= >2, 'NAME'=>'self'),
array('ID'=>5, 'PARENT'=>4, 'NAME'=>'son'),
);
$p = find_parent($data, 'ID', 'PARENT');
$c = find_child($data, 'ID', 'PARENT');
Execution effect:
Copy code
The code is as follows:
Array
(
[1] => Array
(
[ID] => 1
[PARENT] => 0
[NAME] => 祖父
[child] => Array
(
[2] => Array
(
[ID] => 2
[PARENT] => 1
[NAME] => 父亲
[child] => Array
(
[4] => Array
(
[ID] => 4
[PARENT] => 2
[NAME] => 自己
[child] => Array
(
[5] => Array
(
[ID] => 5
[PARENT] => 4
[NAME] => 儿子
)
)
)
)
)
[3] => Array
(
[ID] => 3
[PARENT] => 1
[NAME] => 叔伯
)
)
)
[2] => Array
(
[ID] => 2
[PARENT] => 1
[NAME] => 父亲
[child] => Array
(
[4] => Array
(
[ID] => 4
[PARENT] => 2
[NAME] => 自己
[child] => Array
(
[5] => Array
Son )
[3] => Array
(
[ID] => 3
[PARENT] => 1
[NAME] => Uncle
)
[4] => Array
(
[ID] => 4
Array
🎜> ] => Son
[5] => Array
(
[ID] => 5
[PARENT] => 4
[NAME] => Son
)
)
http://www.bkjia.com/PHPjc/756337.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/756337.htmlTechArticleTwo tree array operation functions without recursion Copy the code as follows: /** * Create a parent node tree Array* Parameter* $ar array, data organized in adjacency list mode* $id array...