Inserting index and value into a two-dimensional array

2

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

Imagining as if it were an array (row x column), I need to insert a column at the end of each row. Here is 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';
    }
}

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

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

    
asked by anonymous 19.10.2017 / 18:40

2 answers

3

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

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

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

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