多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[toc] ## :-: **效果** ![](https://box.kancloud.cn/0fff6d601c10354c805eaa9bb50962a5_569x756.png) ## :-: **代码** ``` php $urlArr = array( 'https://172.16.3.33/resource/js/jquery.min.js', 'https://172.16.3.33/resource/js/unit.js', 'https://172.16.3.33/resource/js/dialog/jquery.artDialog.source.js', 'https://172.16.3.33/test.js', 'https://172.16.3.13/resource/xigua/hello.php', ); $urlTree = arrangeUrlTree($urlArr); //拼接数据 echo "<pre>"; $urlTree = jsonTree($urlTree); //转换json。可以直接给zTree插件使用 //print_r($urlTree,1); $tree = echoTree($urlTree); //根据url生成目录树 echo $tree; /** * 整理url数组 为 url树结构 * @param $arr 一维数组 * @return array * @author xg */ function arrangeUrlTree($arr){ if(!$arr){ return array(); } $returnArr = array(); foreach($arr as $k => $v){ $url = parse_url($v);//分析URL //print_r($url); $hostname = $url['scheme'].'://'.$url['host']; if(!isset($returnArr[$hostname])){ $returnArr[$hostname] = array(); } $pathList = explode('/',$url['path']); $pathList = array_filter($pathList);//去空 $pathList = array_merge($pathList);//重新排序下标 $pathListCount = count($pathList);//长度 $tmpArr = &$returnArr[$hostname];//引用赋值,更新最终数组的值 $treeLevel = 1;//树的深度 为遍历展示用 foreach($pathList as $k2 => $v2){ if($k2 == ($pathListCount-1) ) {//最后一层 则说明是文件 否则为文件夹路径 $tmpArr[] = $v2; //$tmpArr['treeLevel'] = $treeLevel; //等级 }else{ if(!isset($tmpArr[$v2])){ $tmpArr[$v2] = array(); } //$tmpArr['treeLevel'] = $treeLevel; $tmpArr = &$tmpArr[$v2];//重新赋值数组 用于循环整理完完整目录 } $treeLevel += 1; } } return $returnArr; } /** * 根据url树结构 输出 树目录 * @param $urlTree * @return string */ function echoTree($urlTree){ static $treeStr = ''; foreach($urlTree as $k => $v){ $treeLevel = isset($v['treeLevel']) ? $v['treeLevel'] : ( isset($urlTree['treeLevel']) ? ($urlTree['treeLevel']+1) : 1 ); $str = getLevelStr($treeLevel); if(is_array($urlTree[$k])){ $treeStr .= "$str-{$k}<br>"; echoTree($v); }else{ if($k!=='treeLevel'){ $treeStr .= "$str-{$v}<br>"; } } } return $treeStr; } //树深度 返回标识符 function getLevelStr($level){ $level = max(1,$level); $str = ''; for($i=0; $i<$level; $i++){ $str .= "----";//标识符 } return $str; } /** * 生成zTree专用格式。对象型数据。 name children * @param $arr 多维数组 * @return array * @author xg */ function jsonTree($arr){ $rtn = array(); foreach($arr as $k => $v){ if(is_array($v)){ $rtn[] = array( 'name' => $k, 'children' => jsonTree($arr[$k]), ); }else{ $rtn[] = array( 'name' => $v, ); } } return $rtn; } //jsonTree方法,生成这种格式 $test = [ [ 'name' => '测试1', 'children' => [ [ 'name' => '测试2', ] ] ],[ 'name' => '测试3' ] ]; ``` ## :-: **追加子级的思路** ![](https://box.kancloud.cn/59b579fa17b6bfd6d88d5cdb88c3c9ae_1098x513.png)