One-time query n recursive method a
Test data points I
Get all data $pdo = new PDO ("mysql:host=localhost;dbname=lamp108", ' root ', ' root '), $stmt = $pdo->query ("SELECT * FROM Cate2 "); $data = $stmt->fetchall (2), function getcate4 ($data, $pid = 0, $level =0) {$level + +; $cateArr = array ();// Traverse data foreach ($data as $v) {if ($v [' pid '] = = $pid) {//$v[the classification under the current parent ID to $catearr ' level '] = $level;//Put the depth (number of layers) together in $catearr $ Catearr[] = $v;//See if there are subcategories for this classification if there is a continuation to $cateArr $catearr = Array_merge ($CATEARR, Getcate4 ($data, $v [' id '], $level));}} Returns the current categorical data return $CATEARR;} $GETARR = Getcate4 ($data), foreach ($getArr as $v) {echo str_repeat (' | ', $v [' Level ']). ' | -'. $v [' name ']. ' <br/> ';}
Method 21 Recursive N-Times query (for reference only)
function Getcate3 ($pid =0, $level =0) {$cateArr = Array (), $level + +, $pdo = new PDO ("mysql:host=localhost;dbname=lamp108", ' Root ', ' root ');//The first time the PID is 0 is the root classification $stmt = $pdo->query ("select * from Cate2 where pid={$pid}"); $data = $stmt Fetchall (2), foreach ($data as $v) {$v [' level '] = $level; $CATEARR [] = $v; $cateArr =array_merge ($CATEARR, Getcate3 ($v [' id ') ], $level));} return $CATEARR;} $data = Getcate3 (), foreach ($data as $v) {echo str_repeat (' | ', $v [' Level ']). ' | -'. $v [' name ']. ' <br/> ';}
Method 31 queries Traverse a category (three fields)
function Getcate2 ($pid =0, $level =0) {$level + +; $pdo = new PDO ("mysql:host=localhost;dbname=lamp108", ' root ', ' root ');// The first time the PID is 0 is the root classification $stmt = $pdo->query ("select * from Cate2 where pid={$pid}"); $data = $stmt->fetchall (2); foreach ($ Data as $v) {echo str_repeat (' | ', $level). ' | -'. $v [' name ']. $v [' id ']. ' <br/> ';//The ID of the first root category is passed to the next//Next query Level two classification getcate2 ($v [' id '], $level);}} Getcate2 ();
Method Four the simplest infinite classification
function getcate1 () {$pdo = new PDO ("mysql:host=localhost;dbname=lamp108", ' root ', ' root '), $stmt = $pdo->query (" Select *,concat (Path, ', ', id) as FullPath from ' cate1 ' ORDER by FullPath; "); return $stmt->fetchall (2);} $data = Getcate1 (), foreach ($data as $v) {$level = Substr_count ($v [' FullPath '], ', '); Echo str_repeat (' | ', $ level). ' | -'. $v [' name ']. ' <br/> ';}
The program comes from network collection--
Infinite methods of infinite classification