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

php无限分类(递归版本)

PHP中文网
PHP中文网asal
2016-05-25 17:14:221312semak imbas

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



?>
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:数组值拼接成字符串Artikel seterusnya:遍历文件夹下所有文件