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):
hakre
source share