Using RecursiveDirectoryIterator of PHP i am able to create directory tree and can even flatten it using RecursiveIteratorIterator class , but I want to create directory tree structure which TREE component of flex understands . The following is an array structure in php which flex understands.
array('label'=>'rootDirectory','children'=>array(array('label'=>'subFolder1','children'=>array(array('label'=>'file.jpg'))),array('label'=>'EmtptyFolder','children'=>array())));
Please show me a way to create the whole directory structure at server side into the above array format.
Thanks in Advance !!
You may adjust this code to your needs. This is not a copy & paste solution as I needed it for a different UseCase, but it should get you at least halfway to implementing your own solution from it. The key lies in adjusting the methods RecursiveIteratorIterator
will call when traversing the directory tree.
<?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
);
}
}
}