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"
                    )

            )

    )
)
Sven van Zoelen
  • 6,989
  • 5
  • 37
  • 48
way2vin
  • 2,411
  • 1
  • 20
  • 15
  • use explode("/", $path) but why would you want so many nested arrays? – VikingBlooded Jun 20 '14 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 – way2vin Jun 20 '14 at 18:11

1 Answers1

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)
hsz
  • 148,279
  • 62
  • 259
  • 315