PHP递归实现层级树状展现数据

  树状数据展现很常用,今天学习了PHP的递归,也来总结总结!

  PHP代码:

  

function _getTreeList_custom1($data,$parent_id,$depth)
    {
        $return_array = array();
        
        if(is_array($data) && !empty($data))
        {
            foreach($data as $key => $info)
            {
                if($info['parent_id'] == $parent_id)
                {
                    $info['depth'] = $depth;
                    
                    $temp_info = $info;
                    
                    foreach($data as $s_info)
                    {
                        if($s_info['parent_id'] == $info['id'])
                        {
                            $temp_info['sub'] = _getTreeList_custom1($data, $info['id'], $depth+1);
                            break;
                        }
                    }
                    
                    $return_array[] = $temp_info;
                }
            }
        }
        
        return $return_array;
    }
    
    function _getTreeList_custom2($data,$parent_id,$depth)
    {
        $return_array = array();
        
        if(is_array($data) && !empty($data))
        {
            foreach($data as $key => $info)
            {
                if($info['parent_id'] == $parent_id)
                {
                    $info['depth'] = $depth;
                    $temp_info = $info;
                    unset($data[$key]);
                    $sub_list = _getTreeList_custom2($data,$info['id'],$depth+1);
                    
                    if(!empty($sub_list))
                    {
                        $temp_info['sub'] = $sub_list;
                    }
                    
                    $return_array[] = $temp_info;
                }
                    
            }
            
        }
        
        return $return_array;
    }

  

  前台显示:

  

function showTreeOnHtml($treeList)
    {
        echo '<ul>';
        foreach($treeList as $key => $treeInfo)
        {
            echo '<li>';
            echo $treeInfo['name'];
            if(!empty($treeInfo['sub']))
            {
                showTreeOnHtml($treeInfo['sub']);
            }
            echo '</li>';
        }
        echo '<ul>';
            
    }
showTreeOnHtml($treeList);

  

原文地址:https://www.cnblogs.com/zhongJaywang/p/5712923.html