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

php无限分类(递归版本)

PHP中文网
Release: 2016-05-25 17:14:22
Original
1313 people have browsed it

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);



?>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template