2016-04-21 8 views
4

Ich habe ein Array wie:Gebäude Pfade von mehrdimensionalen Arrays in PHP

$tree = array(
    'folder_1' => array(
     'folder_1_1', 
     'folder_1_2' => array(
      'folder_1_2_1', 
      'folder_1_2_2' 
     ), 
     'folder_1_3' 
    ), 
    'folder_2' => array(
     'folder_2_1' => array(
      'folder_2_1_1' => array(
       'folder_2_1_1_1', 
       'folder_2_1_1_2' 
      ) 
     ), 
    ) 
); 

Und ich versuche, ein Array von Pfaden zu bauen:

$paths = array(
    'folder_1', 
    'folder_1/folder_1_1', 
    'folder_1/folder_1_2', 
    'folder_1/folder_1_2/folder_1_2_1', 
    'folder_1/folder_1_2/folder_1_2_2', 
    'folder_2', 
    'folder_2/folder_2_1', 
    ... 
); 

Ich kann nicht scheinen zu finden, ein Weg, dies zu erreichen. Das Problem, auf das ich stoße, ist, dass Ordnernamen Array-Schlüssel, aber auch Array-Elemente sein können.

Dies ist, was ich bisher getan haben, aber ich bin nicht in der Nähe einer Lösung ...

$paths = transform_tree_to_paths($trees); 

function transform_tree_to_paths($trees, $current_path = '', $paths = array()) 
{ 

    if (is_array($trees)) { 
     foreach ($trees as $tree => $children) { 
      $current_path .= $tree . '/'; 
      return transform_tree_to_paths($children, $current_path, $paths); 
     } 
     $paths[] = $current_path; 
     $current_path = ''; 
    } else { 
     $paths[] = $trees; 
    } 

    return $paths; 
} 

Antwort

7

Wie wäre es so etwas?

function gen_path($tree, $parent=null) { 
    $paths = array(); 

    //add trailing slash to parent if it is not null 
    if($parent !== null) { 
     $parent = $parent.'/'; 
    } 

    //loop through the tree array 
    foreach($tree as $k => $v) { 
     if(is_array($v)) { 
      $currentPath = $parent.$k; 
      $paths[] = $currentPath; 
      $paths = array_merge($paths, gen_path($v, $currentPath)); 
     } else { 
      $paths[] = $parent.$v; 
     } 
    } 

    return $paths; 
} 

Sie waren in die richtige Richtung, aber verpasste die Marke ein wenig. Die return-Anweisung vor dem rekursiven Funktionsaufruf in Ihrer Funktion verursachte alles, nachdem die foreach-Schleife nie aufgerufen wurde.

+0

richtig und schnell. +10 –

+1

Das ist perfekt, vielen Dank !! – skirato

0

Hier ist eine andere Lösung, unter Verwendung von RecursiveArrayIterator und RecursiveIteratorIterator:

function generatePaths(array $tree) { 
    $result = array(); 
    $currentPath = array(); 

    $rii = new RecursiveIteratorIterator(new RecursiveArrayIterator($tree), RecursiveIteratorIterator::SELF_FIRST); 
    foreach($rii as $key => $value) { 
    if(($currentDepth = $rii->getDepth()) < count($currentPath)) { 
     array_splice($currentPath, $currentDepth); 
    } 
    $currentPath[] = is_array($value) ? $key : $value; 
    $result[] = implode('/', $currentPath); 
    } 

    return $result; 
} 

PS .: Baconics' solution erscheint etwa doppelt so schnell wie mein zu sein, though.

Verwandte Themen