Inserting index and value into a two-dimensional array

Asked

Viewed 454 times

2

I have a two-dimensional array (it contains data from the database). To go through this data, I use a foreach(). I need to add an index and a value to that index at the end of each foreach iteration().

Imagining as if it were an array (row x column), I need to insert a column at the end of each row. Follow the code below:

foreach($dados as $d) {
    if($d['direta'] == 1 && ($d['idEntidade_evento'] == 0 && $d['idSemana'] == 0)){
        $d['tipo'] =& 'Mensagem instantânea';
    } else if($d['direta'] && $d['idEntidade_evento'] > 0 && $d['idSemana'] == 0){
        $d['tipo'] =& 'Evento';
    } else{
        $d['tipo'] =& 'Avaliação';
    }
}

At the end, I need $data to contain everything (the new index entered in the foreach() )

At the end, $data does not have this index (there is no $data['type']). It is as if nothing is inserted.

2 answers

3


You can do this by modifying the current iteration element with the & it changes/adds the variable value by reference or does not make a copy of the original.

foreach($dados as &$d) {
   $d['nova_chave'] = rand(1,99);
}

1

From what I understand you just want to put a new column, so it’s pretty simple:

foreach($dados as $indice => $d) {
    $dados[$indice]['nova_coluna'] = "Novo dado";
}

Browser other questions tagged

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