Insert data into a multidimensional array

Asked

Viewed 1,589 times

2

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 should be dynamic. That is, I have another array with Keys.

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

and I have the value to be inserted

9999999

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

I know I can’t do

$array.$keys = $valor
because it doesn’t work. What I could do?

  • If possible, provide the code you already have ready, this helps in debugging.

3 answers

1


Something next to that:

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

Suggestion for automation:

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

Exit:

 Array ( [a] => 0 [b] => Array ( [f] => 5 [g] => Array ( [h] => 999999 ) [i] => Array ( [o] => 5 ) ) [c] => 2 [e] => 5 ) 
  • right, how to automate this? kind with a foreach sweeping the Keys?

  • I edited the answer, ta ai a functional example, using the code I suggested :D

  • Really good!! It worked! I’m trying to increase the score and I can’t get...

  • Ué, vote on my answer.

  • @user5978: If you vote on the question Claudio gains points and can vote on your answer too :) @Claudio: if this answer solved your problem you can mark as accepted.

  • I voted, I just couldn’t raise a point using the up arrow..

Show 1 more comment

1

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 whole matrix structure and updates the value where to 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

  • That’s where the problem is... the way you wrote it is something fixed.. my array is dynamic.. Keys are dynamic.. this way as you put it is something fixed.. understand?

  • I understand, more or less... you need to identify the Keys in order to work with an array, otherwise it is not logical to use the array. The value is variable, the key doesn’t have to be, it’s poorly done that. In this case you should rewrite the keys, to a common model.

  • To do this, there is a function called array_map().

  • Another thing you can do is reset the dynamic Keys of that array, using array_values($seuarray);

  • then, as it is in the question... I will have an array that are the Keys... what I would need is something that joins the $array with the $Keys to insert a value...

1

The question is very similar to that: Pre-program parameters to be removed from an object

The difference is that in the other question the problem is to get access and the most complicated is that it was an object and not an array.

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

So using a logic very similar to the one I posted in the other question, I made 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);

Browser other questions tagged

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