0

Hello how can i convert string to array but it should be in nested format. like i show in the example.

first i tried to explode "/" then i try static variable in foreach loop.. but no luck.

i'm beginner & still confused how to do this..

FROM

$str = 'first/second/third';

To

array(
    'first' => array(
        'second' => array(
            'third' => array(

            )
        )
    )
);
1
  • @PravinS tried but it did not came as i expected.. i mean nested format Commented Feb 5, 2014 at 11:36

1 Answer 1

3

Apply cleverness :p

$keys = explode("/",$str);
$result = array();
$ref = &$result;
foreach($keys as $key) {
    $ref[$key] = array();
    $ref = &$ref[$key];
}
unset($ref); // delete the reference
Sign up to request clarification or add additional context in comments.

1 Comment

And thank you for actually using the code I gave you :p So many people take my working code, which I've tested, and come back saying it doesn't work, only to reveal that they had tried to type it themselves rather than copy-pasting and, of course, missed the main point of the answer XD In this case, a hapless user might have entirely missed the & symbols, which of course breaks the entire code, resulting in an empty result 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.