Skip to content

Instantly share code, notes, and snippets.

@jingmian
Created October 19, 2016 08:58
Show Gist options
  • Save jingmian/190b64e3c124e6a892daeca8b38f1c17 to your computer and use it in GitHub Desktop.
Save jingmian/190b64e3c124e6a892daeca8b38f1c17 to your computer and use it in GitHub Desktop.
遍历指定目录的文件夹及其子文件夹
<?php
//遍历指定目录的文件夹及其子文件夹
/*
* @param1 string $dir,要遍历的文件夹
* @param2 int $level,当前遍历的文件夹的深度,默认为0,表示第一层
*
* @return array $arr,一个遍历好的数组
*/
function get_dir($dir,$level = 0){
//建立一个数组保存遍历的结果,但是是静态的,因为需要递归调用的时候,都放到一个数组
static $arr = array();
//判断文件
if(is_dir($dir)){
//打开资源
$o = opendir($dir);
//循环遍历
while($file = readdir($o)){
//将文件加载到静态变量中,但是因为要区分当前文件的层级,所以需要将对应的level也加进去
$arr[] = array($file,$level);
//判断文件是否是.和..
if($file == '.' || $file == '..'){
continue;
}
//判断文件类型
$temp = $dir . '/' . $file;
if(is_dir($temp)){
//子文件夹,递归调用,但是文件层数需要加1
//这里可以不用返回,因为都是在操作静态变量
get_dir($temp,$level + 1);
}
}
}
//最终返回结果
return $arr;
}
$dir = '../';
//调用函数
$files = get_dir($dir);
//循环输出
foreach($files as $file){
echo str_repeat("&nbsp;&nbsp;",$file[1] * 2),$file[0],'<br/>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment