Building paths from a multidimensional array in PHP

I have an array, for example:

$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'
            )
        ),
    )
);

And I'm trying to build an array of paths:

$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',
    ...
);

I cannot find a way to achieve this. The problem I am facing is that folder names can be array keys, but also array elements.

This is what I have done so far, but I'm not next to the solution ...

$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;
}
+4
source share
2 answers

How about something like that?

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;
}

You headed in the right direction, but missed the mark a bit. The return statement before calling the recursive function in your function called everything after the foreach loop was never called.

+7
source

, RecursiveArrayIterator 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, , .

0

All Articles