Skip to content

Instantly share code, notes, and snippets.

@JingwenTian
Created October 24, 2014 09:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JingwenTian/b1187abe850691237a3f to your computer and use it in GitHub Desktop.
Save JingwenTian/b1187abe850691237a3f to your computer and use it in GitHub Desktop.
PHP高效遍历文件夹的方法 http://www.oschina.net/question/260395_162648
<?php
//方法1 递归
function file_list($path)
{
$result = array();
if (is_dir($path) && $handle = opendir($path)) {
while (FALSE !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') continue 1;
$real_path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path.DIRECTORY_SEPARATOR.$file); //realpath($path.DIRECTORY_SEPARATOR.$file);//得到当前文件的全称路径
$result[] = $real_path
if (is_dir($real_path))
$result = array_merge($result, file_list($real_path));
}
closedir($handle);
}
return $result;
}
//方法二,队列
function file_list($path)
{
$result = array();
$queue = array($path);
while($data = each($queue))
{ //3
$path = $data['value'];
if (is_dir($path) && $handle = opendir($path))
{
while (FALSE !== ($file = readdir($handle)))
{ //2
if ($file == '.' || $file == '..') continue 1;
$real_path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path.DIRECTORY_SEPARATOR.$file);
$result[] = $real_path;
if (is_dir($real_path))
$queue[] = $real_path;
}
}
closedir($handle);
}
return $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment