![](/img/trans.png)
[英]PHP delete (.extension) files that are modified after specific time from directory and all sub-directories
[英]Symfony Finder: Get all the files with a specific extension and all the directories within a specific directory
我正在使用Symfony Finder
獲取具有特定擴展名的所有文件以及特定目錄中的所有目錄。
protected function getDirectoryContent(string $directory): array
{
$finder = Finder::create()
->in($directory)
->depth(0)
->name(['*.json', '*.php'])
->sortByName();
return iterator_to_array($finder, true);
}
這樣,該方法只返回某個目錄下所有擴展名為.php
或.json
的文件。 例如,我正在查找的目錄結構如下:
/my/directory/
├── A
├── A.JSON
├── anotherfile.kas
├── file0.ds
├── file1.json
├── file2.php
├── file3.php
├── B
└── C
A
、 B
和C
是目錄。
當我在上面顯示的方法中將上述directory path
作為$directory
參數傳遞時,我得到一個包含以下元素的數組:
file1.json
file2.php
file3.php
太棒了!,但我的問題是,我怎樣才能將所有directories
添加到結果數組中? 我的期望是得到一個如下所示的數組:
A
B
C
file1.json
file2.php
file3.php
在你的情況下,你和finder說話:
結果是錯誤的,因為這兩個規則相互矛盾 - 因為您只想搜索文件。
但是,symfony finder 可以將CallbackIterator
與過濾器模型一起使用。 在這種情況下,您可以添加許多規則或條件。 在你的例子中:
namespace Acme;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
include __DIR__.'/vendor/autoload.php';
$finder = Finder::create();
$finder
->in(__DIR__)
->depth(0)
->filter(static function (SplFileInfo $file) {
return $file->isDir() || \preg_match('/\.(php|json)$/', $file->getPathname());
});
print_r(\iterator_to_array($finder));
在這種情況下,你說:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.