无限分类转换为多维数组

<?php 
 /*$rows = array( 
     array( 
         ‘id’ => 1, 
         ‘name’ => ‘dev’, 
         ‘parentid’ => 0 
     ), 
     array( 
         ‘id’ => 2, 
         ‘name’ => ‘php’, 
         ‘parentid’ => 1 
     ), 
     array( 
         ‘id’ => 3, 
         ‘name’ => ‘smarty’, 
         ‘parentid’ => 2 
     ), 
     array( 
         ‘id’ => 4, 
         ‘name’ => ‘life’, 
         ‘parentid’ => 0 
     )
 );  */
$conn = mysql_connect(‘localhost’,’root’,’123456′);
$db_select=mysql_select_db(“test”);
mysql_query(“set names ‘utf8′”);
$result=mysql_query(“select * from cata”);
while($rs = mysql_fetch_array($result)){
 $rows[] = array(‘id’=>$rs[‘Id’],’name’=>$rs[‘Title’],’parentid’=>$rs[‘Pid’]);

   
 function findChild(&$arr,$id){       
     $childs=array(); 
      foreach ($arr as $k => $v){ 
          if($v[‘parentid’]== $id){ 
               $childs[]=$v;              
          }             
     }         
     return $childs;                
 } 
 function build_tree($root_id){ 
     global $rows; 
     $childs=findChild($rows,$root_id); 
     if(empty($childs)){ 
         return null; 
     } 
    foreach ($childs as $k => $v){ 
        $rescurTree=build_tree($v[‘id’]); 
        if( null !=   $rescurTree){  
        $childs[$k][‘childs’]=$rescurTree; 
        } 
    } 
     return $childs; 
 }   
 $tree=build_tree(0); 
 //echo memory_get_usage(); 
 print_r($tree);     
 ?>

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注