Set values of an array recursively

3

Assuming I have the following array

array(
'chave1' => 'valor1',
'chave2' => array(
    'chave3' => 'valor2',
    'chave4' => array(
        'chave5' => 'valor3'
    )
))

And in this array I need to set the value of key 5, but without going level by level, I could move to a function like this:

setar_valor('chave2.chave4.chave5', 'meu novo valor');

And this function would interpret that every . would be a new level within the array.

I've already broken my mind about it, but I can not think how to do it: /

    
asked by anonymous 14.06.2015 / 23:40

1 answer

1

You can do a function that dumps by reference in this array, following the keys (depth levels) extracted from that string with $niveis = explode('.', $path);

Using & you can go through reference arrays, so when you have $foo = $array[$key]; changing $foo you are changing the value of $array[$key] .

function setar_valor($path, $str, &$array){
    $niveis = explode('.', $path);
    $temp = &$array;
    foreach ( $niveis as $key ) {
        $temp = &$temp[$key];
    }
    $temp = $str;
}

Example: link

The complete code:

$arr = array(
'chave1' => 'valor1',
'chave2' => array(
    'chave3' => 'valor2',
    'chave4' => array(
        'chave5' => 'valor3'
    )
));

function setar_valor($path, $str, &$array){
    $niveis = explode('.', $path);
    $temp = &$array;
    foreach ( $niveis as $key ) {
        $temp = &$temp[$key];
    }
    $temp = $str;
}

setar_valor('chave2.chave4.chave5', 'meu novo valor', $arr);
var_dump($arr);

Result:

array(2) {
  ["chave1"]=>
  string(6) "valor1"
  ["chave2"]=>
  array(2) {
    ["chave3"]=>
    string(6) "valor2"
    ["chave4"]=>
    array(1) {
      ["chave5"]=>
      string(14) "meu novo valor"
    }
  }
}
    
15.06.2015 / 01:19