Insert items into an array

I have an array with a configuration tree:

$cfg = array('global' => array(
    'project'       => 'foo',
    'base_url'      => '/path/',
    'charset'       => 'utf-8',
    'timezone'      => 'Europe/Lisbon',
    'environment'   => 'development'),
    //...
);

I need to insert an element into the tree (or, possibly, change it), such lines as "global:project"and "bar"where the path to the element and its second value are set first. Thus, the value 'foo'in $cfg['global']['project']becomes 'bar'.

Here is the function I need:

function set_cfg($path, $value)
{ /* Alter $cfg with the given settings */ }

So, I start by exploding the path string with ':'and has an array with path keys:

$path = explode(':', $path)

What's next? How can I define (recursively?) The operation of inserting keys into an array $cfg?

+3
source share
4 answers
function set_cfg($path, $value) {
    $path = explode(':', $path);
    $current = &$GLOBALS['cfg']; // variable is global, so get from $GLOBALS
    foreach ($path as $part) {
        $current = &$current[$part];
    }
    $current = $value;
}

If you can be sure that there will always be only two levels of configuration, you can use:

function set_cfg($path, $value) {
    list($first, $second) = explode(':', $path, 2);
    $GLOBALS['cfg'][$first][$second] = $value;
}
+2

, , . , ( ).

+2

This may seem crazy, but something like this:

eval("\$cfg['".str_replace(':', "']['", $path)."'] = ".var_export($value, true).';');
+1
source

I would build a loop that goes through each element in the path when at the end it assigns a value.

The following code is about updating as requested, but it does not deal with empty nodes along the path yet, if this can happen (most likely), be sure to do a loop check and create new arrays as needed.

$node=$cfg;
$i=0;
while($i<count($path)-1)
{
  $node = $node[$path[$i]];
  i++;
}

$node[$path[$i]]=$value;
0
source

Source: https://habr.com/ru/post/1770581/


All Articles