php无限级分类树怎么生成?实现代码

发布时间:2019-12-18编辑:脚本学堂
有关php生成无限级分类树的方法,不需要在内存中递归遍历无限极分类,这里提供一种精简的PHP无限极分类生成树方法,感兴趣的朋友参考下。

php无限级分类树生成函数
 

function generateTree($items){  
    $tree = array();  
    foreach($items as $item){  
        if(isset($items[$item['pid']])){  
            $items[$item['pid']]['son'][] = &$items[$item['id']];  
        }else{  
            $tree[] = &$items[$item['id']];  
        }  
    }  
    return $tree;  
} // www.jb200.com
$items = array(  
    1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),  
    2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),  
    3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),  
    4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),  
    5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),  
);  
print_r(generateTree($items));

输出结果:
Array 

    [0] => Array 
        ( 
            [id] => 1 
            [pid] => 0 
            [name] => 安徽省 
            [son] => Array 
                ( 
                    [0] => Array 
                        ( 
                            [id] => 3 
                            [pid] => 1 
                            [name] => 合肥市 
                            [son] => Array 
                                ( 
                                    [0] => Array 
                                        ( 
                                            [id] => 4 
                                            [pid] => 3 
                                            [name] => 长丰县 
                                        ) 
  
                                ) 
  
                        ) 
  
                    [1] => Array 
                        ( 
                            [id] => 5 
                            [pid] => 1 
                            [name] => 安庆市 
                        ) 
  
                ) 
  
        ) 
  
    [1] => Array 
        ( 
            [id] => 2 
            [pid] => 0 
            [name] => 浙江省 
        ) 
  

 
将以上生成树方法精简到5行:
 

function generateTree($items){  
    foreach($items as $item)  
        $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];  
    return isset($items[0]['son']) ? $items[0]['son'] : array();  
}  
 
/** 
 * 如何取数据格式化的树形数据 
 * www.jb200.com
*/  
$tree = generateTree($items);  
function getTreeData($tree){  
    foreach($tree as $t){  
        echo $t['name'].'<br>';  
        if(isset($t['son'])){  
            getTreeData($t['son']);  
        }  
    }  
}  
getTreeData($tree);