直接上代码:
1 function aryTree($ary, $tagId = 'id', $tagPid = 'pid', $tagSub = '_sub') { 2 3 if(is_array($ary)) { 4 5 $refer = array(); // 创建基于主键(id)的数组引用(映射) 6 7 foreach ($ary as $k => $v) { 8 $refer[$v[$tagId]] =& $ary[$k]; // "引用":不同的变量名访问同一个内容 9 } 10 11 foreach ($ary as $k => $v) { 13 if (isset($refer[$v[$tagPid]])) { 14 $parent =& $refer[$v[$tagPid]]; 15 $parent[$tagSub][$v[$tagId]] =& $ary[$k]; 16 unset($ary[$k]); 17 } 19 } 20 unset($refer); 21 } 22 23 return $ary; 24 }
以下Function是可设置父级级别的代码:
1 function aryTree($ary, $id = 'id', $pid = 'pid', $sub = '_sub', $root = 0) { 2 3 $tree = array(); 4 5 if(is_array($ary)) { 6 7 $refer = array(); 8 9 foreach ($ary as $k => $v) { 10 $refer[$v[$id]] =& $ary[$k]; 11 } 12 13 foreach ($ary as $k => $v) { 14 15 $parentId = $v[$pid]; 16 17 if ($root == $parentId) { 18 19 $tree[$v[$id]] =& $ary[$k]; 20 21 }else{ 22 23 if (isset($refer[$parentId])) { 24 $parent =& $refer[$parentId]; 25 $parent[$sub][$v[$id]] =& $ary[$k]; 26 unset($ary[$k]); 27 } 28 } 29 } 30 unset($refer, $ary); 31 } 32 33 return $tree; 34 }