2013-10-24 37 views
6

我想創建一個文件樹,爲此我需要將文件和目錄的數組轉換爲多維文件樹數組。例如:PHP - 創建動態多維文件樹數組

array 
(
    'file.txt', 
    'dir1/', 
    'dir1/dir2/', 
    'dir1/dir2/dir3/', 
    'dir1/file.txt', 
) 

array 
(
    'file.txt', 
    'dir1' => 
    array 
    (
     'dir2' => 
     array 
     (
      'dir3' => 
      array(), 
     ), 
     'file.txt', 
    ) 
) 

我試過幾個功能來做到這一點,但他們的工作不。我遇到的問題例如,沒有簡單的方法將array ('test','test','test'),'test'轉換爲$array['test']['test']['test'] = 'test'

+0

這些沒有答案的一個幫助你嗎? – AbraCadaver

回答

1

我有那個PHP代碼片段:

<?php 
function wps_glob($dir) { 
    foreach (glob($dir . '/*') as $f) { 
    if(is_dir($f)) { 
     $r[] = array(basename($f) => wps_glob($f)); 
    } 
    else { 
     $r[] = basename($f); 
    } 
    } 
    return $r; 
} 

function wps_files($path) { 
    $wpsdir = Array(
    'root' => $path, 
    'struktur' => wps_glob($path) 
); 
    return $wpsdir; 
} 
?> 

example usage here

3

這裏有一個較短的遞歸一個:

function dir_tree($dir) {  
    $files = array_map('basename', glob("$dir/*")); 
    foreach($files as $file) { 
     if(is_dir("$dir/$file")) { 
      $return[$file] = dir_tree("$dir/$file"); 
     } else { 
      $return[] = $file; 
     } 
    } 
    return $return; 
} 
+0

一直在尋找這樣的東西。我很高興在改造車輪之前看到了這一個。 – 58YtQ2H83m17838963l61BU07Y8622

1

看看到my post here

答案是:strtok會救你。

<?php 

$input = [ 
'/RootFolder/Folder1/File1.doc', 
'/RootFolder/Folder1/SubFolder1/File1.txt', 
'/RootFolder/Folder1/SubFolder1/File2.txt', 
'/RootFolder/Folder2/SubFolder1/File2.txt', 
'/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc', 
]; 

function parseInput($input) { 
    $result = array(); 

    foreach ($input AS $path) { 
    $prev = &$result; 

    $s = strtok($path, '/'); 

    while (($next = strtok('/')) !== false) { 
    if (!isset($prev[$s])) { 
     $prev[$s] = array(); 
    } 

    $prev = &$prev[$s]; 
    $s = $next; 
    } 
$prev[] = $s; 

unset($prev); 
} 
return $result; 
} 

var_dump(parseInput($input)); 

輸出:

array(1) { 
    ["RootFolder"]=> 
    array(2) { 
    ["Folder1"]=> 
    array(2) { 
     [0]=> 
     string(9) "File1.doc" 
     ["SubFolder1"]=> 
     array(2) { 
     [0]=> 
    string(9) "File1.txt" 
     [1]=> 
     string(9) "File2.txt" 
     } 
    } 
    ["Folder2"]=> 
    array(1) { 
     ["SubFolder1"]=> 
     array(2) { 
     [0]=> 
     string(9) "File2.txt" 
     ["SubSubFolder1"]=> 
     array(1) { 
      [0]=> 
      string(9) "File4.doc" 
     } 
     } 
    } 
    } 
}