用于递归搜索文件的PHP最快方法

时间:2017-11-19 06:29:05

标签: php

Hello开发者朋友,

我的任务被描述为我的问题主题。在我的例子中,目录结构足够深,这是目录样本:

D:\DATA\PROGRAM 11\AREA 01\CAB 001\JS 0100 INSIGHT\2008\01 JANUARY\01

我必须在每个最后一个子目录中找到图像文件。我必须在一些参数的帮助下找到文件,一些参数是包含在file_name中的字符串,一些参数帮助系统匹配目录名,然后搜索方法可以更准确。我的代码仍然没有完成,需要很长时间才能完成,大约需要4-5分钟。 请参阅下面的代码,

<?php
function readdirScandir($dir, $extension)
{ 
$files = array();
$root = @scandir($dir, SCANDIR_SORT_NONE);
foreach($root as $entry)
{
    if($entry === '.' || $entry === '..') 
        continue;

    $fullpath = $dir.'/'.$entry;
    if(is_file($fullpath)) 
    {
        if (0 === strcasecmp($extension, pathinfo($fullpath, PATHINFO_EXTENSION)))
            $files[] = $fullpath;
        continue;
    }

    foreach(readdirScandir($fullpath, $extension) as $entry)
    {
        if(0 === strcasecmp($extension, pathinfo($entry, PATHINFO_EXTENSION)))
        {
            $files[] = $entry;
        }
    }
}
return $files;
}


$root_dir = getcwd();

//place this before any script you want to calculate time
$time_start = microtime(true);

// include subdirectories
$dirlist = readdirScandir($root_dir, 'tif');

var_dump($dirlist);

$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<br><b>Total Execution Time:</b> '.$execution_time.' Mins';
?>

我将非常感谢您的建议和帮助。提前谢谢,周末愉快。

1 个答案:

答案 0 :(得分:0)

使用以下方法获取当前目录中包含任何扩展名的文件,并使用

总执行时间:0.0004381​​6566467285分钟

你可以看看glob功能,它比scandir好得多。

if ( ! function_exists('glob_recursive'))
{
    // Does not support flag GLOB_BRACE

    function glob_recursive($pattern, $flags = 0)
    {
        $files = glob($pattern, $flags);

        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
        {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }

        return $files;
    }
}
$time_start = microtime(true);

//put your file extension to get all the files from current directory
$files = glob_recursive('*.png');

var_dump('<pre>', $files);
$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start) / 60;

//execution time of the script
echo '<br><b>Total Execution Time:</b> ' . $execution_time . ' Mins';