首页 >php教程 >PHP源码 >php无限分类(递归版本)

php无限分类(递归版本)

PHP中文网
PHP中文网原创
2016-05-25 17:14:221310浏览

php代码

<?php
$rows = array(
    array(
        &#39;id&#39; => 1,
        &#39;name&#39; => &#39;dev&#39;,
        &#39;parentid&#39; => 0
    ),
    array(
        &#39;id&#39; => 2,
        &#39;name&#39; => &#39;php&#39;,
        &#39;parentid&#39; => 1
    ),
    array(
        &#39;id&#39; => 3,
        &#39;name&#39; => &#39;smarty&#39;,
        &#39;parentid&#39; => 2
    ),
    array(
        &#39;id&#39; => 4,
        &#39;name&#39; => &#39;life&#39;,
        &#39;parentid&#39; => 0
    ),
    array(
        &#39;id&#39; => 5,
        &#39;name&#39; => &#39;pdo&#39;,
        &#39;parentid&#39; => 2
    ),
    array(
        &#39;id&#39; => 6,
        &#39;name&#39; => &#39;pdo-mysql&#39;,
        &#39;parentid&#39; => 5
    ),
    array(
        &#39;id&#39; => 7,
        &#39;name&#39; => &#39;java&#39;,
        &#39;parentid&#39; => 1
    )
);

// 72648
// 84072

function findChild(&$arr,$id){
  
    $childs=array();
     foreach ($arr as $k => $v){
         if($v[&#39;parentid&#39;]== $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][&#39;childs&#39;]=$rescurTree;
       }
   }
    return $childs;
}

 
$tree=build_tree(0);

echo memory_get_usage();

print_r($tree);



?>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn