简体   繁体   中英

Cannot access PHP Object as Array

I am facing a strange problem. It may just be a silly mistake, and I am just missing some basics.

I'm running php 5.6.1 on MAMP.

I have a simple array which I get from a mysql query. Using a foreach loop, I can print_r() each value, which gives me: stdClass Object ( [srno] => 6 [link] => this-is-link )

Now I can echo $obj->srno , and that prints fine. But I can't use echo $obj['srno'] which I was previously using, on an older version of PHP, but- It shows nothing.

Any help really appreciated. Thanks!

If you have a stdClass object and need to address it as an array, you can cast it to array quite easily:

$someObj = new stdClass();
$someObj->foo = "bar";

$someArray = (array)$someObj; // Cast the object to an array

echo $someArray['foo']; // Will give you "bar"

Working example: http://3v4l.org/nni1Y

Of course as comments already pointed out, you may want to look at retrieving your mysql results as an array in the first place.

As you said your results return as an object so you can use it by using $obj->your_field_name to display field value. But your can not use by $obj['field_name'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM