将文件和文件夹列入数组

时间:2013-06-18 03:54:47

标签: php arrays directory subdirectory

我试图将所有子目录中的所有文件列入多维数组。

例如:

文件结构

  • 根/ index.php的
  • Root / folder1 / a.jpg
  • Root / folder1 / b.jpg
  • 根/ folder1中/ c.mov
  • Root / folder2 / aa.jpg
  • Root / folder2 / bb.jpg
  • 根/文件夹2 / cc.mov

我试图像这样得到一个数组()...

$list = array(

     array(
            'type' => 'image',
            'folder'=> 'folder1',
            'imgs' => array('a.jpg', 'b.jpg')
     ),

     array(
            'type' => 'video',
            'folder'=> 'folder1',
            'video' => 'c.mov'
     ),

    array(
            'type' => 'image',
            'folder'=> 'folder2',
            'imgs' => array('aa.jpg', 'bb.jpg')
     ),

     array(
            'type' => 'video',
            'folder'=> 'folder2',
            'video' => 'cc.mov'
     ),

)

2 个答案:

答案 0 :(得分:1)

正如我猜你可能会使用Scandir函数列出文件和文件夹以及特定目录。使用下面的递归函数,你可以得到你的结果。

function listAllFolderFiles($dir){
    $ffs = scandir($dir);
    echo '<ol>';
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            echo '<li>'.$ff;
            if(is_dir($dir.'/'.$ff)) listAllFolderFiles($dir.'/'.$ff);
            echo '</li>';
        }
    }
    echo '</ol>';
}

listAllFolderFiles('Your main dir');

答案 1 :(得分:0)

您可以使用RecursiveIterator创建一个多维数组....

 $path = realpath('Root/');
 $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); 

 $yourArray = array(); 

 foreach ($it as $FileInfo) { 
   $path = $FileInfo->isDir() 
     ? array($FileInfo->getFilename() => array()) 
     : array($FileInfo->getFilename()); 

  for ($depth = $it->getDepth() - 1; $depth >= 0; $depth--) { 
   $path = array($it->getSubIterator($depth)->current()->getFilename() => $path); 
  } 
 $yourArray = array_merge_recursive($yourArray, $path); 
 } 

 print_r($yourArray);