php高效遍历目录文件及子目录

PHPz
Release: 2018-10-08 15:08:33
forward
1001 people have browsed it

如果目录很多,推荐队列方式,递归方式会慢,慢的原因:递归的实现是通过调用函数本身,函数调用的时候,每次调用时要做地址保存,参数传递等

<?php
//递归方式
function read_dir($dir){
	$files=array();
	$dir_list=scandir($dir);
	foreach($dir_list as $file){
		if($file!='..' && $file!='.'){
			if(is_dir($dir.'/'.$file)){
				$files[]=read_dir($dir.'/'.$file);
			}else{
				$files[]=$file;
			}
		}
	}
	return $files;
}
//队列方式 
function read_dir_queue($dir){
	$files=array();
	$queue=array($dir);
	while($data=each($queue)){
		$path=$data['value'];
		if(is_dir($path) && $handle=opendir($path)){
			while($file=readdir($handle)){
				if($file=='.'||$file=='..') continue;
				$files[] = $real_path=$path.'/'.$file;
				if (is_dir($real_path)) $queue[] = $real_path;
			}
		}
		closedir($handle);
	}
	 return $files;
}
print_r(read_dir_queue('D:/webroot/suanfa/dir'));exit;
Copy after login

更多相关教程请访问 php编程从入门到精通全套视频教程

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template