You are here
PHP无限级分类实现(递归+非递归)
星期四, 2017-06-01 09:57 — adminshiping1
版权声明:本文为博主原创文章,未经博主允许不得转载。- <?php
-
-
-
-
-
-
-
- header("content-type:text/html;charset=utf-8");
- $categories = array(
- array('id'=>1,'name'=>'电脑','pid'=>0),
- array('id'=>2,'name'=>'手机','pid'=>0),
- array('id'=>3,'name'=>'笔记本','pid'=>1),
- array('id'=>4,'name'=>'台式机','pid'=>1),
- array('id'=>5,'name'=>'智能机','pid'=>2),
- array('id'=>6,'name'=>'功能机','pid'=>2),
- array('id'=>7,'name'=>'超级本','pid'=>3),
- array('id'=>8,'name'=>'游戏本','pid'=>3),
- );
-
-
- $tree = array();
-
- foreach($categories as $category){
- $tree[$category['id']] = $category;
- $tree[$category['id']]['children'] = array();
- }
-
- foreach($tree as $key=>$item){
- if($item['pid'] != 0){
- $tree[$item['pid']]['children'][] = &$tree[$key];
- if($tree[$key]['children'] == null){
- unset($tree[$key]['children']);
- }
- }
- }
-
- foreach($tree as $key=>$category){
- if($category['pid'] != 0){
- unset($tree[$key]);
- }
- }
-
- print_r($tree);
-
-
- $tree = $categories;
- function get_attr($a,$pid){
- $tree = array();
- foreach($a as $v){
- if($v['pid'] == $pid){
- $v['children'] = get_attr($a,$v['id']);
- if($v['children'] == null){
- unset($v['children']);
- }
- $tree[] = $v;
- }
- }
- return $tree;
- }
- echo "<br/><br/><br/>";
-
- print_r(get_attr($tree,0));
-
来自
http://blog.csdn.net/qishouzhang/article/details/47204359