2

I have a directory structure path like root/path1/path2/path3 I want this to be

Array(
[0] => "root"
[1] => Array
    (
        [0] => "path1"
        [1] => Array
            (
                [0] => "path2"
                [1] => Array
                    (
                        [0] => "path3"
                    )

            )

    )
)
2
  • use explode("/", $path) but why would you want so many nested arrays? Commented Jun 20, 2014 at 18:08
  • explode giving me single dimensional array, like Array ( [0] => root [1] => path1 [2] => path2 [3] => path3 ) Thats is the path i get from my scraping script i need to create similar directory and subdirectory. mkdir("root/path1/path2",0755,true) will create one but i need to do some string function on directory name so I need them individually. Hope you got my idea Commented Jun 20, 2014 at 18:11

1 Answer 1

7

Just try with:

$input  = 'root/path1/path2/path3';
$output = null;

foreach (array_reverse(explode('/', $input)) as $part) {
    $output = $output ? array($part, $output) : array($part);
}

var_dump($output);

Output:

array (size=2)
  0 => string 'root' (length=4)
  1 => 
    array (size=2)
      0 => string 'path1' (length=5)
      1 => 
        array (size=2)
          0 => string 'path2' (length=5)
          1 => 
            array (size=1)
              0 => string 'path3' (length=5)
Sign up to request clarification or add additional context in comments.

1 Comment

any idea how you could reverse this to get the string from the array??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.