PHP无限级分类实现(递归+非递归)

[php]  view plain  copy
  1. /** 
  2.  * Created by PhpStorm. 
  3.  * User: qishou 
  4.  * Date: 15-8-2 
  5.  * Time: 上午12:00 
  6.  */  
  7. //准备数组,代替从数据库中检索出的数据(共有三个必须字段id,name,pid)  
  8. header("content-type:text/html;charset=utf-8");  
  9. $categories = array(  
  10.     array('id'=>1,'name'=>'电脑','pid'=>0),  
  11.     array('id'=>2,'name'=>'手机','pid'=>0),  
  12.     array('id'=>3,'name'=>'笔记本','pid'=>1),  
  13.     array('id'=>4,'name'=>'台式机','pid'=>1),  
  14.     array('id'=>5,'name'=>'智能机','pid'=>2),  
  15.     array('id'=>6,'name'=>'功能机','pid'=>2),  
  16.     array('id'=>7,'name'=>'超级本','pid'=>3),  
  17.     array('id'=>8,'name'=>'游戏本','pid'=>3),  
  18. );  
  19.   
  20. /*======================非递归实现========================*/  
  21. $tree = array();  
  22. //第一步,将分类id作为数组key,并创建children单元  
  23. foreach($categories as $category){  
  24.     $tree[$category['id']] = $category;  
  25.     $tree[$category['id']]['children'] = array();  
  26. }  
  27. //第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。  
  28. foreach($tree as $key=>$item){  
  29.     if($item['pid'] != 0){  
  30.         $tree[$item['pid']]['children'][] = &$tree[$key];//注意:此处必须传引用否则结果不对  
  31.         if($tree[$key]['children'] == null){  
  32.             unset($tree[$key]['children']); //如果children为空,则删除该children元素(可选)  
  33.         }  
  34.     }  
  35. }  
  36. ////第三步,删除无用的非根节点数据  
  37. foreach($tree as $key=>$category){  
  38.     if($category['pid'] != 0){  
  39.         unset($tree[$key]);  
  40.     }  
  41. }  
  42.   
  43. print_r($tree);  
  44.   
  45. /*======================递归实现========================*/  
  46. $tree = $categories;  
  47. function get_attr($a,$pid){  
  48.     $tree = array();                                //每次都声明一个新数组用来放子元素  
  49.     foreach($a as $v){  
  50.         if($v['pid'] == $pid){                      //匹配子记录  
  51.             $v['children'] = get_attr($a,$v['id']); //递归获取子记录  
  52.             if($v['children'] == null){  
  53.                 unset($v['children']);             //如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)  
  54.             }  
  55.             $tree[] = $v;                           //将记录存入新数组  
  56.         }  
  57.     }  
  58.     return $tree;                                  //返回新数组  
  59. }  
  60. echo "


    "
    ;  
  61.   
  62. print_r(get_attr($tree,0));  


转自:http://blog.csdn.net/qishouzhang/article/details/47204359

你可能感兴趣的:(web开发,php)