的所有子目錄我有一個應該是簡單的任務,循環在目錄
- 給定一個路徑,搜索所有兒童(1級深)爲
less
文件夾。 - 如果文件夾中找到與
css
- 添加完整路徑作爲一個關鍵的陣列
- 設定值的關鍵是相同的路徑,但更換
less
裏面少目錄遞歸循環中的所有子目錄 - 以同樣的方式添加子目錄作爲原始目錄
因此,鑑於這種結構
注意:下面的所有項目,除了randomfile是目錄
[email protected]:/var/www/constructor/public/bundles$ tree
.
├── first
│ └── less
│ ├── secondtester
│ └── tester
│ ├── anothersubtester
│ ├── randomfile
│ └── subtester
├── second
│ └── less
│ ├── secondtester
│ └── tester
│ ├── anothersubtester
│ ├── randomfile
│ └── subtester
└── third
└── noless
├── secondtester
└── tester
├── anothersubtester
├── randomfile
└── subtester
18 directories, 3 files
我想這個數組結束(注意我已經在這裏截短的路徑只是爲了使其更易於閱讀)
Array
(
[/b/second/less] => /b/second/css
[/b/second/less/secondtester] => /b/second/css/secondtester
[/b/second/less/tester] => /b/second/css/tester
[/b/second/less/tester/subtester] => /b/second/css/tester/subtester
[/b/second/less/tester/anothersubtester] => /b/second/css/tester/anothersubtester
[/b/first/less] => /b/first/css
[/b/first/less/secondtester] => /b/first/css/secondtester
[/b/first/less/tester] => /b/first/css/tester
[/b/first/less/tester/subtester] => /b/first/css/tester/subtester
[/b/first/less/tester/anothersubtester] => /b/first/css/tester/anothersubtester
)
現在我有下面的代碼,但我不認爲這是完全優化的,例如我知道有RecursiveIteratorIterators
等,但我不能解決如何使用它們來完成這個任務,所以不得不求助於遞歸函數。基本上,我想知道如何寫這個更好地優化:
$directories = array();
$bundlePath = realpath('/public/bundles');
function lessSearcher($lessPath, $cssPath){
$directories = array($lessPath => $cssPath);
$lessDirs = new DirectoryIterator($lessPath);
foreach ($lessDirs as $lessDir) {
//we only want the directories and not the .'s
if ($lessDir->isDot() || !$lessDir->isDir()) continue;
$lessCurrent = $lessPath . '/' . $lessDir->getFileName();
$cssCurrent = $cssPath . '/' . $lessDir->getFileName();
$directories[$lessCurrent] = $cssCurrent;
$directories = array_merge($directories, lessSearcher($lessCurrent, $cssCurrent));
}
return $directories;
}
$bundles = new DirectoryIterator($bundlePath);
foreach ($bundles as $bundle) {
//we only want the directories and not the .'s
if($bundle->isDot() || !$bundle->isDir()) continue;
//we only want the directories that have a less directory
if(!realpath($bundlePath.'/'.$bundle->getFileName().'/less')) continue;
$lessPath = realpath($bundlePath . '/' . $bundle->getFileName()) . '/less';
$cssPath = realpath($bundlePath . '/' . $bundle->getFileName()) . '/css';
$directories = array_merge($directories, lessSearcher($lessPath, $cssPath));
}
我不認爲這是很大的錯誤,說實話,這是否合理快速? –
是的,它似乎運行得足夠快,我只是認爲使用'RecursiveDirectoryIterator'可能會更好,但無法解決如何實際使用它們。 – Hailwood