我已经从目录结构(Create array from directory structure)询问了具有特定结构的数组创建。简单地说。现在我有下一个目录结构:
collection | | ---buildings | | | | | | | ---2.php | | | ---4.php | | ---trees | | ---1.php | ---2.php | ---3.php
我需要迭代这个目录结构并创建下一个数组:
array(
0 => array('category' => 'trees',
'file' => '3.jpg'
),
1 => array('category' => 'trees',
'file' => '2.php'
),
2 => array('category' => 'trees',
'file' => '1.jpg'
),
3 => array('category' => 'buildings',
'file' => '2.jpg'
),
4 => array('category' => 'buildings',
'file' => '4.php'
))
所以我使用RecursiveIterstorIterator和RecursiveDirectoryIterator实现了它。有我的代码:
$path = __DIR__ . '/collection/';
$dir = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
$index = 0;
$paths = [];
foreach ($files as $file) {
$category = $paths[$index-1]['category'];
if (strpos($file->getPathname(), $paths[$index-1]['category'])) {
$paths[$index]['category'] = $paths[$index-1]['category'];
$paths[$index]['file'] = $file->getFilename();
}
else {
if ($paths[$index]['category']) {
$paths[$index]['category'];
} else {
if ($file->isDir()) {
$paths[$index]['category'] = $file->getFilename();
}
$files->next();
$file = $files->current();
if ($file->isFile()) {
$paths[$index]['file'] = $file->getFilename();
}
}
}
$index++;
}
var_dump($paths);
但我认为我的代码是“肮脏的”'并且可以使用RecursiveIteratorIterator和RecursiveDirectoryIterator的另一个功能来避免这种糟糕的if ... else嵌套。 另外我想我并没有考虑所有的用例。 那么请你帮我重构我的代码吧! 谢谢!