根据 PHP 递归读取文件夹生成文件树
class Tree{ public $arr = array(); public $icon = array( '│', '├─', '└─' ); public $ret; public function set_tree($arr = array()) { $this->arr = $arr; } public function get_child($myID) { $newarr = array(); if (is_array($this->arr)) { foreach ($this->arr as $ID => $a) { if ($a['pID'] == $myID) { $newarr[$ID] = $a; } } } return $newarr ? $newarr : false; } //获取带格式数组 public function getArray($myID = 0, $sID = 0, $adds = '') { $number = 1; $child = $this->get_child($myID); if (is_array($child)) { $total = count($child); foreach ($child as $a) { $j = $k = ''; if ($number == $total) { $j .= $this->icon[2]; } else { $j .= $this->icon[1]; $k = $adds ? $this->icon[0] : ''; } $spacer = $adds ? $adds . $j : ''; $a['name'] = $spacer . ' ' . $a['name']; $this->ret[] = $a; $fd = $adds . $k . ' '; $this->getArray($a['ID'], $sID, $fd); $number++; } } return $this->ret; } //select public function get_tree($myID, $str, $sID = 0, $adds = '') { $number = 1; $child = $this->get_child($myID); if (is_array($child)) { $total = count($child); foreach ($child as $a) { $ID = $a['ID']; $j = $k = ''; if ($number == $total) { $j .= $this->icon [2]; } else { $j .= $this->icon [1]; $k = $adds ? $this->icon [0] : ''; } $spacer = $adds ? $adds . $j : ''; $select = $ID == $sID ? 'selected' : ''; $this->ret .= sprintf($str, $ID, $select, $spacer, $a['name']); $this->get_tree($ID, $str, $sID, $adds . $k . ' '); $number++; } } return $this->ret; } //文件夹目录 public function read_all_dir($dir, $onlyDir = true, $ignore = []) { $result = array(); $handle = opendir($dir); if ($handle) { while (($file = readdir($handle)) !== false) { if (in_array($file, $ignore)) continue; if ($file != '.' && $file != '..') { $cur_path = $dir . DIRECTORY_SEParaTOR . $file; if (is_dir($cur_path)) { $result[$file] = $this->read_all_dir($cur_path, $onlyDir); } else { if (!$onlyDir) { $result[] = $file; } } } } closedir($handle); } return $result; } //数组转换 public function arrshift($array, $pID = 0) { static $r = []; static $index = 1; if (is_array($array) && count($array) > 0) { foreach ($array as $k => $v) { $r[] = array( 'ID' => $index, 'pID' => $pID, 'name' => is_array($v) ? $k : $v ); $index++; $this->arrshift($v, $index - 1); } } return $r; }}
使用示例
$tree = new Tree ();//文件夹遍历$data = $tree->read_all_dir(realpath('../file_dir'), false, ['.git', '.IDea', 'vendor']);//转换成[['ID','pID','name']]的二维数组$data = $tree->arrshift($data);$tree->set_tree($data); $data = $tree->getArray();foreach ($data as $value) { echo $value['name']; echo '<br/>'; echo '<br/>';}
推荐教程:《PHP教程》 总结
以上是内存溢出为你收集整理的分享一个生成文件层级树类全部内容,希望文章能够帮你解决分享一个生成文件层级树类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)