Insert data into a multidimensional array

3

I have a multidimensional array


    [0] => Array
        (
            [per] => Array
                (

                    [per_dep] => Array
                        (
                            [0] => 1115921
                            [1] => 1705572
                            [2] => 1126464
                            [3] => 1131324
                        )

                )

        )

And I would like to change the value of per_dep. However, this change must be dynamic. That is, I have another array with the keys.

Array
(
    [0] => 0
    [1] => per
    [2] => per_dep
)

and I have the value to insert

9999999

How could I accomplish this process knowing that the process will be dynamic?

I know I can not do it

$array.$keys = $valor
since it does not work. What could I do?     
asked by anonymous 14.04.2016 / 21:11

3 answers

2

Something close to that:

    $arrayOriginal[$arrayKeys[0]][$arraykeys[1][$arraykeys[2]][$arraykeys[4]] = 9999999;

Automation tip:

  $arrayOriginal = [ 
  'a' => 0,
  'b' =>   [ 'f' => 5 , 
             'g' => [ 'h' => 4 ] ,
             'i' => [ 'o' => 5 ]
            ],
  'c' => 2,
  'e' => 5
  ];


  $arrayKeys = ['b','g','h'];



  $arrayTemp  = &$arrayOriginal;

  $i = 0;

  for ($i = 0;  $i<count($arrayKeys)-1;$i++) {
       $arrayTemp = &$arrayTemp[$arrayKeys[$i]];
  }


  $arrayTemp[$arrayKeys[count($arrayKeys)-1]] = 999999;

  print_r($arrayOriginal);

Output:

 Array ( [a] => 0 [b] => Array ( [f] => 5 [g] => Array ( [h] => 999999 ) [i] => Array ( [o] => 5 ) ) [c] => 2 [e] => 5 ) 
    
14.04.2016 / 21:18
2

The question is very similar to this: Pre program parameters to remove from an object

The difference is that in the other question the problem is getting access and what made it more complicated was that it was an object, not an array.

In PHP, there is the array_reduce () function for this purpose, but for your case, what complicates is that you need to set and not just read.

So using a logic very similar to what I posted in the other question, I did a simple version for your case:

function SetArrayReduce($array, $key, $val)
{
    $r = array();
    $l = function($r) use (&$l, &$key, $val) {
        foreach ($key as $k => $v) {
            if (!isset($key[$k])) {
                break;
            }
            unset($key[$k]);
            if (count($key) < 1) {
                return array($v=>$val);
            }
            $r[$v] = $l($r);
        }
        return $r;
    };

    if (is_string($key)) {
        $key = explode(':', $key);
    }

    $r = $l($r);
    unset($key, $val);
    return array_merge_recursive($array, $r);
}


/*
O array com os dados originais.
*/
$array = array(
    0 => array(
        'per' => array(
            'per_dep' => array(
                0 => 1115921,
                1 => 1705572,
                2 => 1126464,
                3 => 1131324
            )
        )
    )
);

/*
A chave/índice que pretende modificar.
Exemplo, para modificar somente $array[0]['per']['per_dep']

A função SetArrayReduce() aceita uma string como parâmetro.
Apenas precisa definir um delimitador. Por padrão o delimitador é :
$key = '0:per:per_dep';
*/
$key = Array
(
    0 => 0,
    1 => 'per',
    2 => 'per_dep'
);

/*
O array $key pode ser escrito de outras formas:
$key = array(0, 'per', 'per_dep');
$key = array('string1' => 0, 'string2' => 'per', 'string3' => 'per_dep');
O importante é que os valores devem estar na ordem correta pois serão agrupados em cascata.
*/

/*
Remova o comentário da linha abaixo e experimente o resultado usando $key como string.
*/
//$key = '0:per:per_dep';

/*
O valor que deseja atribuir a chave/índice.
*/
$val = 9999999;

/*
Invoca a função e mostra o resultado.
*/
$rs = SetArrayReduce($array, $key, $val);
print_r($rs);
    
15.04.2016 / 16:48
2

To do this in a multidimensional array, being the dynamic keys, it is important to know which key you want to update, I put an array example that takes the entire array structure and updates the value where you find the key you are looking for, using a recursive function, PHP 5 or higher, learn more here :

$seuArray = array( 
  'a' => 0,
  'b' =>   array( 'b1' => 5 , 
                  'b2' => array( 'b2_0' => 4 ) ,
                  'b3' => array( 'b3_0' => 5 )
            ),
  'c' => 2,
  'd' => 5
  );

$saida = replaceValue($seuArray, 'b2_0', array('nova_chave'=>'novo_valor'));


function replaceValue($array, $key, $newValue)
{

    $params = array(
      'newvalue' => $newValue,
      'key'      => $key    
    );

    array_walk_recursive($array, function(&$v, $k) use ($params) {

        if ($k == $params['key']) {
            $v = $params['newvalue'];
        }       
    }); 
    return $array;
}

See the example working on IDEONE

    
14.04.2016 / 21:27