【发布时间】:2018-03-27 04:54:45
【问题描述】:
我需要迭代目录结构并将其推送到具有特殊结构的数组。所以我有下一个目录结构
<pre>
collection
|
|
---buildings
| |
| |
| ---greece
| | |
| | |
| | ---1.php
| | ---2.php
| |
| |
| ---rome
| |
| |
| ---1.php
| ---3.php
|
|
---trees
|
|
---evergreen
| |
| |
| ---1.php
| ---2.php
|
|
---leaves
|
|
---1.php
---2.php
</pre>
因此需要“解析”它并准备下一种格式的数据:
array('collection' => array('category' => 'buildings',
'subcategory' => 'greece',
'type' => 1),
array('category' => 'buildings',
'subcategory' => 'greece',
'type' => 2)),
array('category' => 'buildings',
'subcategory' => 'rome',
'type' => 1),
array('category' => 'buildings',
'subcategory' => 'rome',
'type' => 1),
array('category' => 'buildings',
'subcategory' => 'rome',
'type' => 3),
array('category' => 'trees',
'subcategory' => 'evergreen',
'type' => 1),
array('category' => 'trees',
'subcategory' => 'evergreen',
'type' => 2),
array('category' => 'trees',
'subcategory' => 'leaves',
'type' => 1),
array('category' => 'trees',
'subcategory' => 'leaves',
'type' => 2)
),
我想用 RecursiveDirectoryIterator 来实现它。所以我将“路径”作为参数传递给 RecursiveDirectoryIterator。然后我传递了这个新对象 ReursiveIteratorIterator。之后,我使用“foreach”语句对其进行迭代。所以我创建了下一个代码:
$path = __DIR__ . '/collection/';
$dir = new RecursiveDirectoryIterator($path);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
if (0 === $files->getDepth()) {
$objects['category'] = $file->getBasename();
}
if (1 === $files->getDepth()) {
$objects['subcategory'] = $file->getBasename();
}
}
if ($file->isFile()) {
$objects['fileName'] = $file->getBasename('.php');
continue;
}
}
我希望收到所需数据的数组。 但是这段代码只给了我:
array('category' => 'buildings',
'subcategory' => 'greece',
'fileName' => '1'
)
请帮助我在这项任务中实现我的目标! 谢谢!
【问题讨论】:
-
你在stackoverflow.com/questions/14304935/…和
RecursiveIteratorIterator::CATCH_GET_CHILD看到过这个例子 -
我不明白它对我有什么帮助。如何获得“建筑物”目录。比看看它是否有子目录。如果它有它的名字,则添加到结果数组中。比看子目录是否有文件,如果有名字,则添加到结果数组中。如果子目录有另一个文件,请再看一遍。如果已添加到结果数组。我需要从子文件夹中获取所有文件,添加到结果数组中。之后我需要检查父文件夹('buildings')是否有其他子文件夹。如果有我需要迭代,添加到结果数组。之后我需要拿另一个“收藏”文件夹并重复操作。你能帮帮我吗?
标签: php