Error while displaying array in PHP

Asked

Viewed 153 times

0

I have this array in PHP and I must display the users name and email field. But php display 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:

PHP Error was encountered

Severity: Notice

Message: Undefined index: name

Filename: home/list.php

Line Number: 20

Backtrace

:

PHP Error was encountered

Severity: Notice

Message: Undefined index: email

Filename: home/list.php

Line Number: 21

  • What is the error message? And how are you trying to do that?

  • 2

    And if you do $dados[0]->nome;? Each of the subelements is an object and not an array

  • so work this way: echo $data[0]->name;

  • with faco to display on foreach ??

2 answers

2


It’s a stdClass Object, do it like this:

Suppose 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;
  • How do I put this in while($line = mysql_fetch_assoc($data)){ echo #line[0]["name"];

  • when this code gives error: Fatal error: Cannot use Object of type stdClass as array in D

  • I edited and put an example of how to put this inside the while

  • Only it works this way: echo $data[0]->name;

  • edited again, now have an example inside a foreach, replace the while, try and tell me.

  • worked perfectly, but there is an empty line at the end..

  • how do I eliminate the empty line from the end ??

  • to delete the last item of the array use the array_pop() function, in your case, put before foreach the following: array_pop($data);

Show 3 more comments

0

When you find this error:

Undefined index: email (or whatever)

It means that you are trying to take from the object an indexer 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 whole structure of the variable or object, then you arrive at the following solution:

echo $dados[0]->nome;

Or, still:

foreach($dados as $result){
    echo "O resultado é ". $result->nome;
}

Browser other questions tagged

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