php文件夹遍历的N种办法

<?php
header('Content-type:text/html,charset=utf-8');
function getList($path){
	$list = array();
	$new_dir='';
	$dh=scandir($path);
	$num =count($dh);
	for ($i=0; $i < $num; $i++) { 
		// var_dump($dh[$i]);
		if ($dh[$i] =='.' || $dh[$i] == '..') {
			continue;
		}
		if ($path !='/') {
			$new_dir = $path.'/'.$dh[$i];
		}else{
			$new_dir = $path.$dh[$i];
		}
		
		// var_dump($new_dir);
		if (is_dir($new_dir)) {
			//如果是文件夹
			$list['dir'][]=$new_dir;
			$file_dir=getList($new_dir);//递归开始
    		if ($file_dir['dir']) {
    			//合并文件夹
    			$list['dir']=array_merge($list['dir'],$file_dir['dir']);
    		}
    		if ($file_dir['file']) {
    			//合并文件
    			$list['file']=array_merge($list['file'],$file_dir['file']);
    		}
		}
		if (is_file($new_dir)) {
			$list['file'][]=$new_dir;
		}
	}
	return $list;
}

function getList2($path){

	$list = array();
	$new_dir='';
	// 打开目录,然后读取其内容
	if (is_dir($path)){
	  if ($dh = opendir($path)){
	    while (($file = readdir($dh)) !== false){
	    	if ($file=='.' || $file=='..') {
	    		//.和..跳过
	    		continue;
	    	}
	    	//判断是不是根目录
	    	if ($path !='/') {
				$new_dir=$path.'/'.$file;
			}else{
				$new_dir=$path.$file;
			}
	    	if (is_dir($new_dir)) {
	    		$list['dir'][]=$new_dir;
	    		$file_dir=getList2($new_dir);//递归开始
	    		if ($file_dir['dir']) {
	    			$list['dir']=array_merge($list['dir'],$file_dir['dir']);
	    		}
	    		if ($file_dir['file']) {
	    			$list['file']=array_merge($list['file'],$file_dir['file']);
	    		}
	    	}elseif (is_file($new_dir)) {
	    		$list['file'][]=$new_dir;
	    	}
	    }
	    closedir($dh);
	    return $list;
	  }
	}
}

var_dump(getList('E:\lnmp'));

版权声明:
作者:超级管理员
链接: https://apecloud.ltd/article/detail.html?id=31
来源:猿码云个人技术站
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
/static/admin/img/weixin.jpg/static/admin/img/zfb.jpg
<<上一篇>
mysql常用语句及复习资料
下一篇>>