Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to write this code without an eval() [duplicate]

I have string:

Main.Sub.SubOfSub

And some kind of data, may be a string:

SuperData

How I can transform it all to this array above?

Array
(
[Main] => Array
    (
        [Sub] => Array
            (
                [SubOfSub] => SuperData
            )

    )

)

Thanks for help, PK

like image 387
PiKey Avatar asked Aug 10 '26 17:08

PiKey


1 Answers

Given the values

$key = "Main.Sub.SubOfSub";
$target = array();
$value = "SuperData";

Here's some code I have lying around that does what you need¹:

$path = explode('.', $key);
$root = &$target;

while(count($path) > 1) {
    $branch = array_shift($path);
    if (!isset($root[$branch])) {
        $root[$branch] = array();
    }

    $root = &$root[$branch];
}

$root[$path[0]] = $value;

See it in action.

¹ Actually it does slightly more than that: it can be trivially encapsulated inside a function, and it is configurable on all three input values (you can pass in an array with existing values, and it will expand it as necessary).

like image 170
Jon Avatar answered Aug 13 '26 07:08

Jon