There are several forms of recursive infinite class classification, and here are just a few examples of the three common types:
The first type: Returns an array with a sort:
<?php$data = Array (1 = = Array (' id ' = = 1, ' pid ' = 0, ' user_name ' = ' one ',), 2 = = Array (' id ' = = 2, ' pid ' = 1, ' user_name ' + ', '), 3 = = Array ( ' id ' = 3, ' pid ' = 1, ' user_name ' + ', ', ' 4 = ' array (' id ' = = 4, ' pid ' = 2, ' user_name ' = ' three ', ' 5 = = Array ' (' id ' = 5, ' pid ' = 2, ' user_name ' = ' three ',), 6 = = Array (' id ' = = 6, ' pid ' = 5, ' user_name ' = ' f ') we ',),); function gencate ($data, $pid = 0, $level = 0) {Static $result = array (); $result = ($level = = 0)? Array (): $result; $prefix = ($level = = 0)? ": Str_repeat ('-', $level); foreach ($data as $key + $row) {if ($row [' pid '] = = $pid) {$row [' user_name '] = $prefix. $row [' User_name ']; $result [] = $row [' user_name ']; Gencate ($data, $row [' id '], $level + 1); }} return $result;} Echo ' <pre> '; $result = Gencate ($data);p rint_r ($result); exit; >
The second type: Returns the HTML string form:
function gettreehtml ($data, $pId) { $html = '; foreach ($data as $k = + $v) { if ($v [' pid '] = = $pId) { $html. = "<li>". $v [' user_name ']; $html. = Gettree ($data, $v [' id ']); $html = $html. "</li>"; } } Return $html? ' <ul> '. $html. ' </ul> ': $html;}
The third type: Returns a multidimensional array form:
function Gettreearray ($data, $pId = 0) { $tree = array (); foreach ($data as $key + $value) { if ($value [' pid '] = = $pId) { $value [' childrens '] = Gettree ($data, $v alue[' id ']); $tree [] = $value; } } return $tree;}