0

I need to take a multidimensional array that defines a file tree structure and convert it to an array of relative paths. I see plenty of answers on how to do the opposite.

I need this:

$file_tree = [
  'img',
  'js' => [
    'src',
    'min',
    'libraries' => ['jquery.js']
  ],
  'src' => [
    'controller' => ['user']
  ]
];

To become this:

$file_paths = ['img','js/src','js/min','js/libraries/jquery.js','src/controller/user'] 
Arkanoid
  • 1,165
  • 8
  • 17

1 Answers1

0

You can use recursion.

Make a processArray($o, $a, $f, $b = false) The parameters are

$o - input array

$a - accumulator array

$f - file path accumulator

$b - this is to check if the function is first called

function processArray($o, $a = array(), $f = array() , $b = true){
    foreach( $o as $k => $v ) {
        if ( is_array( $v ) ) {
            $f[] = $k;
            if ( $b ) $f = array($k);
            $a = processArray( $v, $a, $f, false );
        } else {
            $r = implode('/',$f);
            $a[] = $r === '' ? $v : $r . '/' . $v;
        }
    }

    return $a;
}

$result = processArray( $file_tree ); //Call the function

echo "<pre>";
print_r( $result );
echo "</pre>";

This will result to:

Array
(
    [0] => img
    [1] => js/src
    [2] => js/min
    [3] => js/libraries/jquery.js
    [4] => src/controller/user
)
Eddie
  • 26,593
  • 6
  • 36
  • 58