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.

2
  • 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? Commented Oct 4, 2010 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? Commented Oct 4, 2010 at 16:16

1 Answer 1

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) {
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

my var_dump looks like this: array(1) { ["test"]=> array(1) { ["uri"]=> array(1) { ["to"]=> array(1) { ["heaven"]=> array(0) { } } } } }
i would like to be able to reverse this back to a string again. any idea how ?
@TarranJones this answer stackoverflow.com/questions/1319903/… seems to be nice and short

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.