Raj
Raj

Reputation: 1083

String to Array Conversion

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(

            )
        )
    )
);

Upvotes: 0

Views: 91

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

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

Upvotes: 3

Related Questions