2013-10-24 9 views
6

Voglio creare un albero di file, e per questo scopo ho bisogno di convertire un array di file e directory in un array di file tree multidimensionale. Per esempio:PHP - crea un albero di file dinamico multidimensionale

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

a

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

Ho provato diverse funzioni per raggiungere questo obiettivo, ma non di loro ha lavorato. Il problema che ho riscontrato, ad esempio, non è un modo semplice per convertire uno array ('test','test','test'),'test' in $array['test']['test']['test'] = 'test'.

+0

Ha fatto una di queste risposte aiutare? – AbraCadaver

risposta

1

devo frammento di PHP per questo:

<?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

Ecco un breve ricorsiva uno:

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

State cercando qualcosa di simile. Sono contento di averlo visto prima di aver reinventato la ruota. – 58YtQ2H83m17838963l61BU07Y8622

1

Date un'occhiata a my post here.

La risposta è: strtok ti salverà.

<?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)); 

uscita:

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" 
     } 
     } 
    } 
    } 
} 
Problemi correlati