Home > php教程 > PHP源码 > 巧妙使用php引用实现无限分类,输出层级数组,不用递归

巧妙使用php引用实现无限分类,输出层级数组,不用递归

PHP中文网
Release: 2016-05-25 17:08:50
Original
1160 people have browsed it

数据表字段,id,parentid。 
父分类parentid=0,子分类的parentid=父id。 

function getDataTree($rows, $id='id',$pid = 'parentid',$child = 'child',$root=0) {      $tree = array(); // 树  
        if(is_array($rows)){
             $array = array();
             foreach ($rows as $key=>$item){
             $array[$item[$id]] =& $rows[$key];
         }
         foreach($rows as $key=>$item){
             $parentId = $item[$pid];
             if($root == $parentId){
                 $tree[] =&$rows[$key];
             }else{
                 if(isset($array[$parentId])){
                     $parent =&$array[$parentId];
                     $parent[$child][]=&$rows[$key];
                 }
             }
         }
     }
     return $tree;
}
Copy after login
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