I need to iterate directory structure and push it to array with special structure. So I have next directories structure
<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>
So need to 'parse' its and prepare data in next format:
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)
),
I think to implement it with RecursiveDirectoryIterator. So I passed 'path' as parameter to RecursiveDirectoryIterator. Then I passed this new object ReursiveIteratorIterator. After that I used 'foreach' statement to iterate it. So I create next code:
$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;
}
}
I expected to receive arrays of needed data. But this code gives me only:
array('category' => 'buildings',
'subcategory' => 'greece',
'fileName' => '1'
)
Please, help me to achive my goal in this task! Thank you!