/** * Create parent node tree Array * parameter * $ar array, adjacency list organized data * $id array as primary key subscript or association key name * $pid Array as the parent key subscript or association key name * Returns a multidimensional array **/functionFind_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 Array, adjacency list organized data * $id array as the primary key in the Subscript or association key name * $pid Array as the parent key subscript or association key name * Returns a multidimensional array **/functionFind_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;} $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 '); Print_r($c);
Execution effect:
Array( [1] = =Array([ID]= 1[PARENT]= 0[NAME]=Grandpa [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]=uncles)) ) [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]=uncles) [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))
The above introduces the PHP recursive algorithm php tree-do not need recursion, including the PHP recursive algorithm content, I hope the PHP tutorial interested in a friend helpful.