Doubt - Array php return [duplicate]

0

I'm new to php , and I came across the following problem. I have a function that returns an array that comes from the database.

$teste = dados($conexao);

And I do:

print_r($teste);

It returns me the following data:

Array (
    [0] => Array (
        [nome] => Maria
        [idade] => 26
    ) 
    [1] => Array (
        [nome] => Joao
        [idade] => 18
    )
)

Now comes the problem, I want to add one of several different information, eg:

$nomeJoao = $teste[1].nome;
print_r($nomeJoao);

I get the following error on screen:

  

Warning: Use of undefined constant name - assumed 'name' (this will throw an error in a future version of PHP)

     

Notice: Array to string conversion

    
asked by anonymous 26.09.2018 / 16:36

3 answers

1

No PHP the "." is used for concatenation and not for referencing attributes of an array. To reference a property in associative array you need to pass the name of the property.

$teste = [['nome'=>'João', 'idade'=>20], ['nome'=>'Maria', 'idade'=>25]];
print_r( $teste[0]['nome']); // Aqui eu pego o nome do primeiro array
    
26.09.2018 / 16:41
0

If you want to reference a position of a array , you should do this in the following way (considering your example):

Array (
    [0] => Array (
        [nome] => Maria
        [idade] => 26
    ) 
    [1] => Array (
        [nome] => Joao
        [idade] => 18
    )
)

var_dump($teste[1]['nome']);
  

Joao

    
26.09.2018 / 16:41
0

In a given item

$teste[0]['indice'] = 'valor';

foreach to save on all

foreach ($teste as $key => $value){
 $value['indice'] = 'valor';
}

more questions for foreach php foreach php.net

    
26.09.2018 / 16:44