Error displaying array in PHP

0

I have this array in PHP and should display the users name and email field. However, php displays an error message:

array(4) 
    { 
        [0]=> object(stdClass)#25 (5) 
            { 
                ["idusuario"]=> string(1) "2" 
                ["nome"]=> string(5) "admin" 
                ["email"]=> string(15) "[email protected]" 
                ["senha"]=> string(3) "123" 
                ["status"]=> string(1) "1" 
            } 
        [1]=> object(stdClass)#26 (5) 
            { 
                ["idusuario"]=> string(1) "3" 
                ["nome"]=> string(5) "teste" 
                ["email"]=> string(15) "[email protected]" 
                ["senha"]=> string(3) "123" 
                ["status"]=> string(1) "0" 
            } 
    }

PHP code

<?php

   echo $dados["0"]["nome"];
   echo $dados["1"]['email'];
?>

Error message:

  

A PHP Error was encountered

     

Severity: Notice

     

Message: Undefined index: name

     

Filename: home / list.php

     

Line Number: 20

     

Backtrace

:

  

A PHP Error was encountered

     

Severity: Notice

     

Message: Undefined index: email

     

Filename: home / list.php

     

Line Number: 21

    
asked by anonymous 07.10.2017 / 19:10

2 answers

2

It's a stdClass Object, so do:

Let's suppose that in your code the array is in $ data

// printar o campo nome dentro do loop
foreach ($dados as $dado) {
    echo $dado->nome;
}

// printar o campo nome do primeiro item da array
echo $dados[0]->nome;
    
07.10.2017 / 19:16
0

When you encounter this error:

  

Undefined index: email (or whatever)

It means that you are trying to get an indexer from the object that does not exist (a position that does not exist).

A good solution is to give this command die(vardump($minha_variavel)); , it will show the entire structure of the variable or object, so you arrive in the following solution:

echo $dados[0]->nome;

Or, further:

foreach($dados as $result){
    echo "O resultado é ". $result->nome;
}
    
10.03.2018 / 13:11