php打印文本tree树状结构图
我想用php打印某目录文本格式的树状图,但我在网上找了很多基本都是输出tree状结构的数据,也找到了一些只用空格代替的下级的文本tree,这都不是我想要的。我认为至少tree格式结构清晰明了具有网络结构的文本tree才是我想要的。例如cmd控制台输出的目录机构图,目录网络结构由├ │ ├ └ 组成。那只能自己写了,好了不多说了,先看最终效果吧。
最终效果
bootstrap/ ├ css/ │ ├ bootstrap.css │ ├ bootstrap.css.map │ ├ bootstrap.min.css │ └ bootstrap.min.css.map └ js/ ├ bootstrap.js ├ bootstrap.js.map ├ bootstrap.min.js └ bootstrap.min.js.map
树形结构数据
设想打印以上效果,那必须保证数据具有父级子集关系的tree数据结构。如:
Array ( [0] => Array ( [name] => css/ [children] => Array ( [0] => Array ( [name] => css/bootstrap.css ) [2] => Array ( [name] => css/bootstrap.min.css ) ) ) [1] => Array ( [name] => js/ [children] => Array ( [0] => Array ( [name] => js/bootstrap.js ) [2] => Array ( [name] => js/bootstrap.min.js ) ) ) )
编码,根据目录路径获取tree树状数据结构数组:
/**
* 根据目录路径获取tree树状结构数组
* @param string $path 目录路径
* @param mixed $root 跟目录
* @return array|null
*/
function tree_files($path, $root = false) {
if (!is_dir($path))
return null;
if ($root === false)
$root = $path;
if (substr($path, strlen($path) - 1) != '/')
$path .= '/';
$files = array();
$handle = opendir($path);
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$path2 = $path . $file;
if (is_dir($path2)) {
$data['name'] = substr($path2 . '/', strlen($root));
$children = tree_files($path2, $root);
if (!empty($children)) {
$data['children'] = $children;
}
$files[] = $data;
} else {
$files[]['name'] = substr($path2, strlen($root));
}
}
}
return $files;
}生成文本tree
根据具有父子关系的tree数据,打印文本形式的tree树状目录结构图。
/**
* 输出文本格式的树型关系结构图
* @param array $list tree状数组
* @param array $parent 父项
* @param string $print 输出树形文本
* @return string 树形文本
*/
function print_list_tree($list, $parent=null, &$print=''){
$count = count($list);
foreach ($list as $key=>&$item){
$item['count'] = $count;
$item['index'] = $key+1;
if(isset($parent['tags'])){ //父元素是否存在tree型关系图标排列
$item['tags'] = array_merge($parent['tags'] ,isset($item['tags'])?$item['tags']:[]);
$total = count($item['tags']);
$item['tags'][$total-1] = $item['tags'][$total-1]=='├ ' ? '│ ' : ' '; //重置末位关系图标
}
$item['tags'][] = $item['count'] > $item['index'] ? '├ ' : '└ '; //加入该元素关系图标
$print .= implode('',$item['tags']).$item['name']."\n"; //输出该元素关系图
$child = isset($item['children']) ? $item['children'] : [];
if(!empty($child)){
$item['children'] = print_list_tree($child, $item, $print);
}
}
$list = null;
return $print;
}调用方法
print_r("bootstrap-5.0.0/\n");
print_r(print_list_tree(tree_files("C:/Users/XQ/Desktop/bootstrap-5.0.0/")));输出:
bootstrap-5.0.0/ ├ css/ │ ├ css/bootstrap.css │ └ css/bootstrap.min.css └ js/ ├ js/bootstrap.js └ js/bootstrap.min.js
好了,收工。如有不足之处希望指出!
原创文章,转载请注明出处:https://www.weizhixi.com/article/110.html
