首页 > php教程 > php手册 > 生成树型结构(比如省市区),树型结构省市区

生成树型结构(比如省市区),树型结构省市区

WBOY
发布: 2016-06-13 08:39:12
原创
1209 人浏览过

生成树型结构(比如省市区),树型结构省市区

<br /><?<span>php
</span><span>header</span>("Content-type: text/html; charset=utf-8"<span>);

</span><span>function</span> generateTree(<span>$items</span><span>)
{
    </span><span>$tree</span> = <span>array</span><span>();
    </span><span>foreach</span>(<span>$items</span> <span>as</span> <span>$item</span><span>){
        </span><span>if</span>(<span>isset</span>(<span>$items</span>[<span>$item</span>['pid'<span>]])){
            </span><span>$items</span>[<span>$item</span>['pid']]['son'][] = &<span>$items</span>[<span>$item</span>['id'<span>]];
        }</span><span>else</span><span>{
            </span><span>$tree</span>[] = &<span>$items</span>[<span>$item</span>['id'<span>]];
        }
    }
    </span><span>return</span> <span>$tree</span><span>;
}<br />//需要注意的一点,数组的key值必须与id值保持一致
</span><span>$items</span> = <span>array</span><span>(
    </span>1 => <span>array</span>('id' => 1, 'pid' => 0, 'name' => '安徽省'),
    2 => <span>array</span>('id' => 2, 'pid' => 0, 'name' => '浙江省'),
    3 => <span>array</span>('id' => 3, 'pid' => 1, 'name' => '合肥市'),
    4 => <span>array</span>('id' => 4, 'pid' => 3, 'name' => '长丰县'),
    5 => <span>array</span>('id' => 5, 'pid' => 1, 'name' => '安庆市'),<span>
);
</span><span>echo</span> "<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">"<span>;
</span><span>print_r</span>(generateTree(<span>$items</span>));
登录后复制
登录后复制

上面方法的优化:

php header("Content-type: text/html; charset=utf-8"); 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(); } //需要注意的一点,数组的key值必须与id保持一致 $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' => '安庆市'), ); echo "
"<span>;
</span><span>print_r</span>(generateTree(<span>$items</span>));
登录后复制
View Code

 

结果:

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板