在PHP中动态形成具有增量深度的数组

时间:2009-11-27 15:07:24

标签: php arrays recursion

我想使用函数递归扫描文件夹,并将每次扫描的内容分配给数组。

使用next()或foreach递归数组中的每个连续索引很简单 - 但是如何动态地向数组添加深度层(没有将其硬编码到函数中)给了我一些问题。这是一些伪的:

function myScanner($start){

    static $files = array();

    $files = scandir($start);
    //do some filtering here to omit unwanted types

    $next = next($files);


    //recurse scan

    //PROBLEM: how to increment position in array to store results
    //$next_position = $files[][][].... ad infinitum

    //myScanner($start.DIRECTORY_SEPARATOR.$next);
}

任何想法?

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

// $array is a pointer to your array
// $start is a directory to start the scan
function myScanner($start, &$array){
  // opening $start directory handle
  $handle = opendir($start);

  // now we try to read the directory contents
  while (false !== ($file = readdir($handle))) {
    // filtering . and .. "folders"
    if ($file != "." && $file != "..") {
      // a variable to test if this file is a directory
      $dirtest = $start . DIRECTORY_SEPARATOR . $file;

      // check it
      if (is_dir($dirtest)) {
        // if it is the directory then run the function again
        // DIRECTORY_SEPARATOR here to not mix files and directories with the same name
        myScanner($dirtest, $array[$file .  DIRECTORY_SEPARATOR]);
      } else {
        // else we just add this file to an array
        $array[$file] = '';
      }
    }
  }

  // closing directory handle
  closedir($handle);
}

// test it
$mytree = array();
myScanner('/var/www', $mytree);

print "<pre>";
print_r($mytree);
print "</pre>";

答案 1 :(得分:0)

尝试使用此功能(并根据您的要求进行编辑):

function getDirTree($dir,$p=true) {
    $d = dir($dir);$x=array();
    while (false !== ($r = $d->read())) {
        if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) {
            $x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false));
        }
    }

    foreach ($x as $key => $value) {
        if (is_dir($dir.$key."/")) {
            $x[$key] = getDirTree($dir.$key."/",$p);
        }
    }

    ksort($x);
    return $x;
}

返回已排序的目录数组。