相思资源网 Design By www.200059.com

你还在用浪费时间又浪费内存的递归遍历无限极分类吗,看了该篇文章,我觉得你应该换换了。

这是我在OSChina上看到的一段非常精简的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;
}
$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']) "codetitle">复制代码 代码如下:
/**
 * 如何取数据格式化的树形数据
 */
$tree = generateTree($items);
function getTreeData($tree){
    foreach($tree as $t){
        echo $t['name'].'<br>';
        if(isset($t['son'])){
            getTreeData($t['son']);
        }
    }
}
getTreeData($tree);

标签:
PHP,无限极分类,生成树

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“PHP超牛逼无限极分类生成树方法”

暂无PHP超牛逼无限极分类生成树方法的评论...