First set up the classification information table:
1 CREATE TABLE IF not EXISTS' Category ' (2' CategoryId 'smallint(5) unsigned not NULLAuto_increment,3' ParentID 'smallint(5) unsigned not NULL DEFAULT '0',4' CategoryName 'varchar( -) not NULL,5 PRIMARY KEY(' categoryId ')6) ;
Insert several data:
1 INSERT into' Category ' (' categoryId ', ' parentid ', ' CategoryName ')VALUES2(1,0,'PHP'),3(2,0,'Java'),4(3,0,'C + +'),5(4,1,'PHP Basics'),6(5,1,'PHP Open Source data'),7(6,1,'PHP Framework'),8(7,2,'Java Se'),9(8,2,'Java EE'),Ten(9,2,'Java Me'), One(Ten,3,'BASIC Programming for C + +'), A( One,3,'d/C + + system development'), -( A,3,'C Embedded Programming'), -( -,3,'C + + application development'), the( -, -,'C + + desktop application development'), -( the, -,'C + + game development');
Here is the PHP code:
1<?PHP2 //PHP Infinite Class classification3 4 //Get direct subcategories of a category5 functionGetsons ($categorys,$catId=0){6 $sons=Array();7 foreach($categorys as $item){8 if($item[' ParentID ']==$catId)9 $sons[]=$item;Ten } One return $sons; A } - - //get all subcategories of a category the functionGetsubs ($categorys,$catId=0,$level=1){ - $subs=Array(); - foreach($categorys as $item){ - if($item[' ParentID ']==$catId){ + $item[' Level ']=$level; - $subs[]=$item; + $subs=Array_merge($subs, Getsubs ($categorys,$item[' CategoryId '],$level+1)); A at } - - } - return $subs; - } - in //get all the parent categories for a category - //Method one, recursive to functionGetparents ($categorys,$catId){ + $tree=Array(); - foreach($categorys as $item){ the if($item[' CategoryId ']==$catId){ * if($item[' ParentID ']>0) $ $tree=Array_merge($tree, Getparents ($categorys,$item[' ParentID ']));Panax Notoginseng $tree[]=$item; - Break; the } + } A return $tree; the } + - //method Two, iteration $ functionGetParents2 ($categorys,$catId){ $ $tree=Array(); - while($catId! = 0){ - foreach($categorys as $item){ the if($item[' CategoryId ']==$catId){ - $tree[]=$item;Wuyi $catId=$item[' ParentID ']; the Break; - } Wu } - } About return $tree; $ } - - - //Test Section A $pdo=NewPDO (' Mysql:host=localhost;dbname=test ', ' root ', ' 8888 '); + $stmt=$pdo->query ("SELECT * from category ORDER by CategoryId"); the $categorys=$stmt->fetchall (PDO::FETCH_ASSOC); - $ $result=getsons ($categorys, 1); the foreach($result as $item) the Echo $item[' CategoryName ']. ' <br> '; the Echo' ; the - $result=getsubs ($categorys, 0); in foreach($result as $item) the Echo str_repeat(‘ ‘,$item[' Level ']).$item[' CategoryName ']. ' <br> '; the Echo' ; About the $result=getparents ($categorys, 7); the foreach($result as $item) the Echo $item[' CategoryName ']. ' >> '; + Echo' ; - the $result=getparents2 ($categorys, 15);Bayi foreach($result as $item) the Echo $item[' CategoryName ']. ' >> '; the?>
Here is the result of the run:
Infinite pole Classification of PHP