Get first element in PHP stdObject

匿名 (未验证) 提交于 2019-12-03 01:46:01

问题:

I have an object (stored as $videos) that looks like this

object(stdClass)#19 (3) {   [0]=>   object(stdClass)#20 (22) {     ["id"]=>     string(1) "123"    etc... 

I want to get the ID of just that first element, without having to loop over it.

If it were an array, I would do this:

$videos[0]['id'] 

It used to work as this:

$videos[0]->id 

But now I get an error "Cannot use object of type stdClass as array..." on the line shown above. Possibly due to a PHP upgrade.

So how do I get to that first ID without looping? Is it possible?

Thanks!

回答1:

Simply iterate its using {}

Example:

$videos{0}->id 

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and above use this

$videos{0}['id'] 


回答2:

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {   [0]=>   object(stdClass)#20 (22) {     ["id"]=>     string(1) "123"   etc... 

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object 

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element $key = key($obj); 

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4



回答3:

Correct:

$videos= (Array)$videos; $video = $videos[0]; 


回答4:

You could loop on the object maybe and break in the first loop... Something like

foreach($obj as $prop) {    $first_prop = $prop;    break; // or exit or whatever exits a foreach loop... }  


回答5:

much easier:

$firstProp = current( (Array)$object ); 


回答6:

$videos->{0}->id worked for me.

Since $videos and {0} both are objects, so we have to access id with $videos->{0}->id. The curly braces are required around 0, as omitting the braces will produce a syntax error : unexpected '0', expecting identifier or variable or '{' or '$'.

I'm using PHP 5.4.3.

In my case, neither $videos{0}->id and $videos{0}['id'] worked and shows error :

Cannot use object of type stdClass as array.



回答7:

Playing with Php interactive shell, Php 7:

Only current is working with object.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!