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

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

PHP中文网
PHP中文网Original
2016-05-25 17:08:501155browse

数据表字段,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;
}
Statement:
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