PHP中的数组递归目录;相对映射到绝对值

时间:2011-11-15 16:06:26

标签: php path directory-structure

我将结果从递归目录列表中拉到数组中,并且想知道是否有更好的(读取更快,简洁等等。)方式。具体来说,我正在创建一个数组:

path_relative_to_somedir => absolute_path

现在我有:

$map = array();
$base_realpath = realpath('/path/to/dir');
$iterator = new \RecursiveDirectoryIterator($base_realpath);
foreach((new \RecursiveIteratorIterator($iterator)) as $node){
    $node_realpath = $node->getRealpath();
    $map[substr($node_realpath, strlen($base_realpath) + 1)] = $node_realpath;
}

这很好(貌似),但我担心边缘情况,虽然我确信它们会在测试中出现,但其他人可能会指出。所以:

  • 是否有更好的(读取更快,更准确,更可靠)方式来获取相对于$base_realpath的节点路径?
  • 我应该将glob()readdir()等选项视为更快的替代方案吗? (这是一个有点时间敏感的操作,我在PHP中看到了一个与PHP中的目录递归有关的问题,在回答中会有一些基准,会在找到时链接

- 问题结束 -


- 可能不必要的细节开始 -

目的;我正在为应用程序创建虚拟工作目录,以便对给定文件的调用映射到实际文件。例如:( 我正在详细说明如果有人根据我实际做的事情总体上有更好的替代方法

鉴于dir1是虚拟工作目录的“根”,我们希望合并到dir2

path/                       path/
|                           |
+-- to/                     +-- to/
    |                           |
    +-- dir1/                   +-- dir2/
        |                           |
        +-- script1.php             +-- script2.php
        |                           |
        +-- script2.php             +-- subdir/
        |                               | 
        +-- subdir/                     +-- script4.php
            |               
            +-- script3.php 

它会产生如下数组:

[script1.php] => path/to/dir1/script1.php
[script2.php] => path/to/dir2/script2.php
[subdir/script3.php] => path/to/dir1/subdir/script3.php
[subdir/script4.php] => path/to/dir2/subdir/script4.php

请注意,合并会替换现有的相对路径,并且每个元素都会映射到它的实际路径。我只是在这里使用array_replace(),这是方法片段:

public function mergeModule($name){
    $path = realpath($this->_application->getPath() . 'modules/' . $name);
    if(!is_dir($path) || !is_readable($path)){
        // @todo; throw exception
    }
    $map = array();
    try{
        $directory_iterator = new \RecursiveDirectoryIterator($path);
        foreach((new \RecursiveIteratorIterator($directory_iterator)) as $node){
            $node_realpath = $node->getRealpath();
            $map[substr($node_realpath, strlen($path) + 1)] = $node_realpath;
        }
    }catch(\Exception $exception){
        // @todo; handle
    }
    $this->_map = array_replace($this->_map, $map);
}

1 个答案:

答案 0 :(得分:0)

如果您正在寻找以递归方式列出目录的更快方法,则可以尝试使用外部程序。快得多:)

exec('tree -if /var/www',$tree);
foreach($tree as $key => $path) {
    if ( !$path ) // Ignore the summary ex "5 directories, 30 files"
       break;

    // Do something with the file/dir path
}

如果您只需要.php文件,则可以使用find命令。

find . -name "*.php"
相关问题