您可以根据需要调整此代码。这不是一个复制粘贴解决方案,因为我需要它用于不同的用例,但它至少可以让您从中实现自己的解决方案。关键在于调整方法
RecursiveIteratorIterator
将在遍历目录树时调用。
<?php
/**
* Prints a Directory Structure as an Nested Array
*
* This iterator can be used to wrap a RecursiveDirectoryIterator to output
* files and directories in a parseable array notation. Because the iterator
* will print the array during iteration, the output has to be buffered in
* order to be captured into a variable.
*
* <code>
* $iterator = new RecursiveDirectoryAsNestedArrayFormatter(
* new RecursiveDirectoryIterator('/path/to/a/directory'),
* RecursiveIteratorIterator::SELF_FIRST
* );
* ob_start();
* foreach($iterator as $output) echo $output;
* $output = ob_get_clean();
* </code>
*
*/
class RecursiveDirectoryAsNestedArrayFormatter extends RecursiveIteratorIterator
{
/**
* Prints one Tab Stop per current depth
* @return void
*/
protected function indent()
{
echo str_repeat("\t", $this->getDepth());
}
/**
* Prints a new array declaration
* return void
*/
public function beginIteration()
{
echo 'array(', PHP_EOL;
}
/**
* Prints a closing bracket and semicolon
* @return void
*/
public function endIteration()
{
echo ');', PHP_EOL;
}
/**
* Prints an indented subarray with key being the current directory name
* @return void
*/
public function beginChildren()
{
$this->indent();
printf(
'"%s" => array(%s',
basename(dirname($this->getInnerIterator()->key())),
PHP_EOL
);
}
/**
* Prints a closing bracket and a comma
* @return void
*/
public function endChildren()
{
echo '),', PHP_EOL;
}
/**
* Prints the indented current filename and a comma
* @return void
*/
public function current()
{
if ($this->getInnerIterator()->current()->isFile()) {
printf(
'%s"%s",%s',
str_repeat("\t", $this->getDepth() +1),
$this->getInnerIterator()->current()->getBasename(),
PHP_EOL
);
}
}
}