3

I'm looking to take a string such as

"/test/uri/to/heaven"

and turn it into a multi-dimensional, nested array such as:

array(
    'var' => array(
        'www' => array(
            'vhosts' => array()            
        ),
    ),
);

Anyone got any pointers? I've had a look through Google and the search here, but I've not seen anything.

hakre
  • 193,403
  • 52
  • 435
  • 836
BeesonBison
  • 1,053
  • 1
  • 17
  • 27
  • 1
    Doing this usually makes little sense, which is why there's no `explode()` function that works this way. What do you need this for? – Pekka Oct 04 '10 at 16:14
  • Well, explode gives me a flat array. I was wondering how I get the results of an explode, retaining the depth of the path in the string as per my example? – BeesonBison Oct 04 '10 at 16:16

1 Answers1

5

Here is a quick non recursive hack:

$url   = "/test/uri/to/heaven";
$parts = explode('/',$url);

$arr = array();
while ($bottom = array_pop($parts)) {        
    $arr = array($bottom => $arr);
}

var_dump($arr);

Output:

array(1) {
  ["test"]=>
  array(1) {
    ["uri"]=>
    array(1) {
      ["to"]=>
      array(1) {
        ["heaven"]=>
        array(0) {
        }
      }
    }
  }
}
Arosha De Silva
  • 597
  • 8
  • 18
ITroubs
  • 11,094
  • 4
  • 27
  • 25
  • 1
    my var_dump looks like this: array(1) { ["test"]=> array(1) { ["uri"]=> array(1) { ["to"]=> array(1) { ["heaven"]=> array(0) { } } } } } – ITroubs Oct 04 '10 at 16:23
  • i would like to be able to reverse this back to a string again. any idea how ? – TarranJones Apr 13 '15 at 14:45
  • @TarranJones this answer http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array seems to be nice and short – ITroubs Apr 13 '15 at 16:57