网站地图    收藏   

主页 > php专栏 > php数组查询 >

php数组转换成树的几个例子 - php数组

来源:自学PHP网    时间:2014-11-25 21:17 作者: 阅读:

[导读] 下面我整理了一些常用的数组转换成树的实例与大家一起学习,我想大家都会很喜欢这篇文章的 Php代码如下:*$sourceArr原来的数组*$key主键*$parentKey与主键关联的父主键*$childrenKey生成的孩子...

php数组转换成树的几个例子

下面我整理了一些常用的数组转换成树的实例与大家一起学习,我想大家都会很喜欢这篇文章的.Php代码如下:

  1. $sourceArr 原来的数组  
  2. $key 主键  
  3. $parentKey 与主键关联的父主键  
  4. $childrenKey 生成的孩子的键名  
  5. *  
  6. */   
  7.    
  8. function arrayToTree($sourceArr$key$parentKey$childrenKey)   
  9. {   
  10.     $tempSrcArr = array();   
  11.     foreach ($sourceArr as  $v)   
  12.     {   
  13.         $tempSrcArr[$v[$key]] = $v;   
  14.     }   
  15.     $i = 0;   
  16.     $count = count($sourceArr);   
  17.     for($i = ($count - 1); $i >=0; $i--)   
  18.     {   
  19.         if (isset($tempSrcArr[$sourceArr[$i][$parentKey]]))   
  20.         {   
  21.            $tArr = array_pop($tempSrcArr);   
  22.            $tempSrcArr[$tArr[$parentKey]][$childrenKey] = (isset($tempSrcArr[$tArr[$parentKey]][$childrenKey]) && is_array($tempSrcArr[$tArr[$parentKey]][$childrenKey])) ? $tempSrcArr[$tArr[$parentKey]][$childrenKey] : array();   
  23.            array_push ($tempSrcArr[$tArr[$parentKey]][$childrenKey], $tArr);   
  24.         }   
  25.     }   
  26.     return $tempSrcArr;   
  27. }   

PHP代码如下:

  1.  * 将数组转换成树  
  2.  * 例子:将 array(  
  3.             array('id'=>1,'parentId' => 0,'name'=> 'name1')  
  4.             ,array('id'=>2,'parentId' => 0,'name'=> 'name2')  
  5.             ,array('id'=>4,'parentId' => 1,'name'=> 'name1_4')  
  6.             ,array('id'=>15,'parentId' => 1,'name'=> 'name1_5')  
  7.     ); 
  8.  
  9. /*转换成  
  10.  * Array(  
  11.     [1] => Array([id] => 1  
  12.             [parentId] => 0  
  13.             [name] => name1  
  14.             [children] => Array(  
  15.                     [0] => Array([id] => 15,[parentId] => 1,[name] => name1_5)  
  16.                     [1] => Array([id] => 4,[parentId] => 1,[name] => name1_4) 
  17.                 )  
  18.         )  
  19.     [2] => Array([id] => 2,[parentId] => 0,[name] => name2)  
  20.  
  21. */ 

* @param array $sourceArr 要转换的数组 

* @param string $key 数组中确认父子的key,例子中为“id” 

* @param string $parentKey 数组中父key,例子中为“parentId” 

* @param type $childrenKey 要在树节点上索引子节点的key,例子中为“children” 

* @return array 返回生成的树 

PHP代码如下:

  1. function arrayToTree($sourceArr$key$parentKey$childrenKey)   
  2. {   
  3.     $tempSrcArr = array();   
  4.    
  5.     $allRoot = TRUE;   
  6.     foreach ($sourceArr as  $v)   
  7.     {   
  8.         $isLeaf = TRUE;   
  9.         foreach ($sourceArr as $cv )   
  10.         {   
  11.             if (($v[$key]) != $cv[$key])   
  12.             {   
  13.                 if ($v[$key] == $cv[$parentKey])   
  14.                 {   
  15.                     $isLeaf = FALSE;   
  16.                 }   
  17.                 if ($v[$parentKey] == $cv[$key])   
  18.                 {   
  19.                     $allRoot = FALSE;   
  20.                 }   
  21.             }   
  22.         }   
  23.         if ($isLeaf)   
  24.         {   
  25.             $leafArr[$v[$key]] = $v;   
  26.         }   
  27.         $tempSrcArr[$v[$key]] = $v;   
  28.     }   
  29.     if ($allRoot)   
  30.     {   
  31.         return $tempSrcArr;   
  32.     }   
  33.     else   
  34.     {   
  35.         unset($v$cv$sourceArr$isLeaf);   
  36.         foreach ($leafArr as  $v)   
  37.         {   
  38.             if (isset($tempSrcArr[$v[$parentKey]]))   
  39.             {   
  40.                 $tempSrcArr[$v[$parentKey]][$childrenKey] = (isset($tempSrcArr[$v[$parentKey]][$childrenKey]) && is_array($tempSrcArr[$v[$parentKey]][$childrenKey])) ? $tempSrcArr[$v[$parentKey]][$childrenKey] : array();   
  41.                 array_push ($tempSrcArr[$v[$parentKey]][$childrenKey], $v);  
  42.                 unset($tempSrcArr[$v[$key]]);   
  43.             }   
  44.         }   
  45.         unset($v);   
  46.         return arrayToTree($tempSrcArr$key$parentKey$childrenKey);   
  47.     }   

PHP代码,递归方法:

  1. $rows = array(   
  2.     0 => array('id' => 1, 'name' => '菜单1''parentId' => 0)   
  3.     , 1 => array('id' => 2, 'name' => '菜单2''parentId' => 0)   
  4.     , 2 => array('id' => 3, 'name' => '菜单3''parentId' => 0)   
  5.     , 3 => array('id' => 4, 'name' => '菜单1_1''parentId' => 1)   
  6.     , 4 => array('id' => 5, 'name' => '菜单1_2''parentId' => 1)   
  7.     , 5 => array('id' => 6, 'name' => '菜单2_1''parentId' => 2)   
  8. );   
  9. print_r(getTree($rows, 0, 'id''parentId'));  

代码如下:

  1. /**  
  2.  * 数组根据父id生成树  
  3.  * @staticvar int $depth 递归深度  
  4.  * @param array $data 数组数据  
  5.  * @param integer $pid 父id的值  
  6.  * @param string $key id在$data数组中的键值  
  7.  * @param string $chrildKey 要生成的子的键值  
  8.  * @param string $pKey 父id在$data数组中的键值  
  9.  * @param int $maxDepth 最大递归深度,防止无限递归  
  10.  * @return array 重组后的数组  
  11.  */   
  12. function getTree($data$pid = 0, $key = 'id'$pKey = 'parentId'$childKey = 'child'$maxDepth = 0){   
  13.     static $depth = 0;   
  14.     $depth++;   
  15.     if (intval($maxDepth) <= 0)   
  16.     {   
  17.         $maxDepth = count($data) * count($data);   
  18.     }   
  19.     if ($depth > $maxDepth)   
  20.     {   
  21.         exit("error recursion:max recursion depth {$maxDepth}");   
  22.     }   
  23.     $tree = array();   
  24.     foreach ($data as $rk => $rv)   
  25.     {   
  26.         if ($rv[$pKey] == $pid)   
  27.         {   
  28.             $rv[$childKey] = getTree($data$rv[$key], $key$pKey$childKey$maxDepth);   
  29.             $tree[] = $rv;   
  30.         }   
  31.     }   
  32.     return $tree;   
  33. }  

一个实例,代码如下:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
  2. <html xmlns="http://www.w3.org/1999/xhtml"
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
  6. <title>TREE</title> 
  7. <style type="text/css"
  8. /*树的全局CSS*/ 
  9. .kyp_tree{ 
  10. font: 12px/2.5 verdana; 
  11. float:left;display:inline; 
  12. .kyp_tree dd{ 
  13. margin:0;padding:0; 
  14. margin-left:20px; 
  15. /*链接*/ 
  16. .kyp_tree dl a{ 
  17. font-size:12px; 
  18. color:#333; 
  19. text-decoration:none; 
  20. .kyp_tree dl a:hover, .kyp_tree dd dt.red_sub a{ 
  21. font-size:12px; 
  22. color:#AE0002; 
  23. /*一级dl*/ 
  24. .kyp_tree dl{ 
  25. border-bottom:1px dashed #ccc; 
  26. margin:0;padding:0; 
  27. /*次级dl*/ 
  28. .kyp_tree dl dl, .kyp_tree dl.last{ 
  29. border:none; 
  30. .kyp_tree dd dt.currentClass{ 
  31. background:url(tree_top.gif) no-repeat 0 -24px;  
  32. /*一级标题*/ 
  33. .kyp_tree dt{ 
  34. background:url(tree_top.gif) no-repeat 2px -57px; 
  35. padding-left:15px; 
  36. cursor:pointer; 
  37. font-size:13px; 
  38. height:30px; 
  39. line-height :27px; 
  40. line-height :32px9; 
  41. /*子标题*/ 
  42. .kyp_tree dd dt{ 
  43. background:url(tree_arrow.gif) no-repeat 2px 10px; 
  44. font-size:12px; 
  45. /*一级张开样式*/ 
  46. .kyp_tree dt.open{ 
  47. background:url(tree_top.gif) no-repeat 2px 12px;  
  48. /*张开样式*/ 
  49. .kyp_tree dd dt.open{ 
  50. background:url(tree_arrow.gif) no-repeat 0 -25px;  
  51. /*没有子节点的样式*/ 
  52. .kyp_tree dt.nosub{ 
  53. background:none; 
  54. </style> 
  55. <script type="text/javascript"
  56. //<![CDATA[ 
  57. jQuery.fn.createTree = function (fn, ini){ 
  58. var $ = jQuery, ini = Object(ini); 
  59. this.find('dd').hide(); 
  60. this.children('dl:last').addClass('last'); 
  61. this.find('dt', this).each(function (){ 
  62. var nosub = $(this).next('dd').size() == 0; 
  63. if (nosub) { 
  64. $(this).addClass('nosub'); 
  65. if (ini.id && ini.id == $(this).attr('classify')) { 
  66. $(this).parents('dd').show().prev('dt').addClass('open'); 
  67. $(this).addClass('red_sub'); 
  68. if (nosub) { 
  69. $(this).addClass('currentClass'
  70. }else
  71. $(this).next('dd').show(); 
  72. $(this).addClass('open'
  73. }).click(function (e){ 
  74. var dd = $(this).next('dd'), 
  75. isClose = dd.css('display') == 'none'
  76. if (dd.size()) { 
  77. if (isClose) { 
  78. dd.show(); 
  79. $(this).addClass('open'
  80. }else
  81. dd.hide(); 
  82. $(this).removeClass('open'
  83. }  
  84. return fn && fn.call(this, e, dd) 
  85. }); 
  86. if (ini.mx) { 
  87. this.find('dt').click(function (e){ 
  88. var J = $(this); 
  89. if (J.next('dd').size()) { 
  90. if (J.hasClass('open')) { 
  91. J.parent().siblings('dl').children('dd').hide(); 
  92. J.parent().siblings('dl').children('dt').removeClass('open'); 
  93. J.next('dd').show(); 
  94. J.addClass('open')  
  95. }  
  96. })  
  97. }; 
  98. (function ($){ 
  99. $(function (){ 
  100. $('#tree_wrap').createTree(function (e, dd){//回调(事件, 下一个dd) 
  101. $('#show').html(this.innerHTML+dd.size()) 
  102. }, {mx: 1, id: 200})// mx是否互斥, id 当前类别 
  103. }); 
  104. })(jQuery) 
  105. //]]> 
  106. </script> 
  107. </head> 
  108. <body> 
  109. <?php 
  110. // 树组的顺序即是分类的顺序,因此前当分类的下级子类一定要紧随其后 
  111. $treearray
  112. 1 => array('id'=>1, 'cname'=>'一级分类''pid'=>0), 
  113. 100 => array('id'=>100, 'cname'=>'特意加进去的二级分类''pid'=>1), 
  114. 101 => array('id'=>101, 'cname'=>'特意加进去的二级分类2222222222''pid'=>1), 
  115. 2 => array('id'=>2, 'cname'=>'二级分类''pid'=>1), 
  116. 3 => array('id'=>3, 'cname'=>'三级分类''pid'=>2), 
  117. 4 => array('id'=>4, 'cname'=>'四级分类''pid'=>3), 
  118. 5 => array('id'=>5, 'cname'=>'四级分类2''pid'=>3), 
  119. 200 => array('id'=>200, 'cname'=>'55555''pid'=>5), 
  120. 6 => array('id'=>6, 'cname'=>'另一级分类''pid'=>0), 
  121. 7 => array('id'=>7, 'cname'=>'First First First''pid'=>0), 
  122. 8 => array('id'=>8, 'cname'=>'First First First''pid'=>7), 
  123. ); 
  124. // 指定分类ID,返回子类量(不进行深度递归) 
  125. function getChildTotal($id
  126. global $tree
  127. $total = 0; 
  128. foreach($tree as $value
  129. if ($id == $value['pid']) 
  130. $total++;  
  131. return $total
  132.  
  133. // 指定分类ID,并返回数组(不进行深度递归) 
  134. function getChildArray($id
  135. global $tree
  136. $array = array(); 
  137. foreach($tree as $key=>$value
  138. if ($id == $value['pid']) 
  139. $array[$key] = $value
  140. return $array
  141.  
  142. // 递归查询方式将树数组转换成HTML嵌套树 
  143. function getTreeHTML($tree,$level = 0) 
  144. if ($tree
  145. $level += 1; 
  146. foreach($tree as $id => $node
  147. $html .= "<dl>"
  148. $html .= '<dt classify="'.$node['id'].'"><a href="http://www.baidu.com/">'.$node['cname']."</a></dt>"
  149. if (getChildTotal($node['id'])) 
  150. $tree_last = getChildArray($node['id']); 
  151. $html .= '<dd>'
  152. $html .= getTreeHTML($tree_last,$level); 
  153. $html .= '</dd>'
  154. $html .= '</dl>'
  155. return $html
  156. $html = getTreeHTML( getChildArray(0) ); 
  157. echo '<div id="tree_wrap" class="kyp_tree">'
  158. echo $html
  159. echo '</div><div id="show" style="clear:both;border-top:1px solid red"></div>'
  160. ?> 
  161. </body> 
  162. </html> 

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论