<?php//Infinite pole classification//parent value, is the column of the parent column ID is/*0 Anhui hefei Beijing Haidian zhongguancun Hebei Shijiazhuang * * $area = array (' ID ' =>1, ' name ' = ' Anhui ', ' p Arent ' =>0), array (' ID ' =>2, ' name ' = = ' Beijing ', ' parent ' =>0), array (' ID ' =>3, ' name ' = = ' Haidian ', ' Parent ' =>2 ), array (' ID ' =>4, ' name ' = ' Zhongguancun ', ' parent ' =>3), array (' ID ' =>5, ' name ' = ' Hefei ', ' parent ' =>1), array (' ID ' =>6, ' name ' = ' on ', ' parent ' =>3 ', array (' ID ' =>7, ' name ' = ' Hebei ', ' parent ' =>0), array (' ID ' =>8, ' Name ' = ' Shijiazhuang ', ' parent ' =>7),/*1. is to find the descendants of the designated column, that is, descendants of the tree 2. is to find the parent column of the specified column/parent column ... Top column, that is, family tree *///find sub-column function Findson ($arr, $id =0) {//$id column of the son? A: Array loop over, who's the value of the parent = $id, who is his son $sons = array ();//Sub-column array foreach ($arr as $v) {if ($v [' parent '] = = $id) {$sons [] = $v;} }return $sons;} Print_r (Findson ($area, 0));//Find descendants tree static property call/* Static static variable declared in a function no matter how many times this function is called, it is useful to inherit the variable directly after it is initialized once in recursion. Summary 1. The properties and methods of the decorated class are static properties, static methods 2.static::method (), and delay binding 3. In a function/method, declare a static variable with */function subtree ($arr, $id =0, $lev =1) {static $ Subs = Array (); Descendant array foreach ($arr as $v) {if ($v [' parent '] = = $id){$v [' lev '] = $lev; $subs [] = $v;//For example, array (' ID ' =>1, ' name ' = ' Anhui ', ' parent ' =>0), subtree ($arr, $v [' id '], $lev + 1) ;}} return $subs;} /*print_r (Subtree ($area, 0,1)), $tree = subtree ($area, 0,1), foreach ($tree as $v) {# Code...echo str_repeat (' ', $v [' Lev ']), $v [' name '], ' <br/> ';} *///the second type without static variable function subtree2 ($arr, $id =0, $lev =1) {$subs = array ();//descendant array foreach ($arr as $v) {if ($v [' parent '] = = $id) {$v [' lev '] = $lev; $subs [] = $v;//For example, array (' ID ' =>1, ' name ' = ' Anhui ', ' parent ' =>0), $subs = Array_merge ($subs, Subtree2 ($arr, $v [' id '], $lev + 1));}} return $subs;} $tree = Subtree2 ($area, 0,1), foreach ($tree as $v) {echo str_repeat (' ', $v [' Lev ']), $v [' name '], ' <br/> ' ;}? >
PHP using recursive write infinite pole classification