Set values of an array recursively

Asked

Viewed 589 times

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 each . would be a new level inside the array.

I’ve broken my head with it, but I can’t think of how to do it :/

  • Cakephp organizes exactly this way, I’ll see how they do it, I’ll look in the documentation

  • It is necessary to interpret chave2.chave4.chave5 by dividing each level by .? it wouldn’t be easier to go all the way array and change the value according to the key?

  • @qmechanik would be easier yes, but would have conflict if you have more than one 5 key at different array levels

1 answer

1


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

Using & you can go by reference arrays, so when you have $foo = $array[$key]; changing $foo you’re 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: https://ideone.com/H6D3Og

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);

Upshot:

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

    thanks for the help man, thanks anyway

Browser other questions tagged

You are not signed in. Login or sign up in order to post.