String with array structure in array

I have a line:

Main.Sub.SubOfSub 

And some data may be a string:

 SuperData 

How can I convert all of this to this array above?

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

)

Thanks for the help, PC

+7
source share
2 answers

Given the values

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

Here is some code that I was lying doing 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; 

Look at the action .

ΒΉ Actually, this is a little more: it can be trivially encapsulated inside a function and configured for all three input values ​​(you can pass an array with existing values, and it will expand it if necessary).

+11
source

Just as Jon suggested (and requesting chat feedback), a reference / variable alias is useful here to go through a dynamic key stack. Therefore, you just need to sort through all the subsections and, finally, set the value:

 $rv = &$target; foreach(explode('.', $key) as $pk) { $rv = &$rv[$pk]; } $rv = $value; unset($rv); 

The link allows you to use the stack instead of recursion, which is usually more meager. In addition, this code prevents overwriting existing elements in the $target array. Full example:

 $key = "Main.Sub.SubOfSub"; $target = array('Main' => array('Sub2' => 'Test')); $value = "SuperData"; $rv = &$target; foreach(explode('.', $key) as $pk) { $rv = &$rv[$pk]; } $rv = $value; unset($rv); var_dump($target); 

Output:

 array(1) { ["Main"]=> array(2) { ["Sub2"]=> string(4) "Test" ["Sub"]=> array(1) { ["SubOfSub"]=> string(9) "SuperData" } } } 

Demo

Related Question (s):

+5
source

All Articles