我目前正在開發一個 php 檔案索引器,我需要創建一個遞回函式來創建一個陣列,該陣列將包含父檔案夾的檔案和子檔案夾串列,子檔案夾也是包含其檔案及其子檔案夾的陣列(等.. .)。因為它是一個學校專案,所以我不能使用 DirectoryRecursiveIterator 及其兄弟 RecursiveIterator 和 DirectoryIterator。我的問題是它掃描父檔案夾并找到子檔案夾和檔案,但沒有進入子檔案夾來查找檔案和子檔案夾。
代碼
<?php
class H5AI
{
// Properties
private $_tree;
private $_path;
// Construct
public function __construct($_path)
{
$_tree = [];
$parent = $_tree;
print_r($this->getFiles($_path, $parent));
}
// Methods
public function getPath()
{
return $this->_path;
}
public function getTree()
{
return $this->_tree;
}
public function getFiles($path, $parent)
{
//Opening the directory
$dirHandle = opendir($path);
while (false !== $entry = readdir($dirHandle)) {
//If file found
if (!is_dir($path . DIRECTORY_SEPARATOR . $entry)) {
array_push($parent, $entry);
}
// When subdirs found (ignore . & ..)
else if (is_dir($path . DIRECTORY_SEPARATOR . $entry) && $entry !== "." && $entry !== "..") {
$newPath = $path . DIRECTORY_SEPARATOR . $entry;
$parent[$entry] = [];
$this->getFiles($newPath, $parent[$entry]);
}
}
return $parent;
}
}
// Calling function
$h5a1 = new H5AI($argv[1]);
// Command I use in the terminal
php index.php "./test_dir"
//Output
Array
(
[sub_test_dir] => Array
(
)
[0] => test.css
[sub_test_dir2] => Array
(
)
[1] => test.js
[2] => test.html
)
uj5u.com熱心網友回復:
class H5AI {
public function __construct(string $path) {
print_r($this->getFiles($path));
}
public function getFiles(string $directory): array {
$handle = opendir($directory);
$entries = [];
while (true) {
$entry = readdir($handle);
if ($entry === false) {
break;
}
$path = $directory . DIRECTORY_SEPARATOR . $entry;
if (is_file($path) && !str_starts_with($entry, '.')) {
$entries[] = $entry;
} elseif (is_dir($path) && !in_array($entry, [ '.', '..', '$RECYCLE.BIN' /* add other dir names to exclude here */ ])) {
$entries[$entry] = $this->getFiles($path);
}
}
closedir($handle);
return $entries;
}
}
uj5u.com熱心網友回復:
您正在創建一個單獨的陣列,其中包含您想要的內容,但未插入到您的父陣列中。你一切都好,你只需要一點點修復:
//...
else if (is_dir($path . DIRECTORY_SEPARATOR . $entry) && $entry !== "." && $entry !== "..") {
$newPath = $path . DIRECTORY_SEPARATOR . $entry;
$parent[$entry] = [];
$parent[$entry] = $this->getFiles($newPath, $parent[$entry]); // <-- fix is on this line
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441397.html
下一篇:如何在SteelBankCommonLisp(SBCL)中使用`class-direct-superclasses`和`class-precedence-list`?
