获取PHP stdObject中的第一个元素 [英] Get first element in PHP stdObject
问题描述
我有一个看起来像这样的对象(存储为$ videos)
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...
我只想获取第一个元素的ID,而不必循环访问它.
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']
它以前是这样工作的:
$videos[0]->id
但是现在我在上面显示的行上收到一个错误无法将stdClass类型的对象用作数组...".可能是由于PHP升级所致.
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.
那么我如何不循环就获得第一个ID?有可能吗?
So how do I get to that first ID without looping? Is it possible?
谢谢!
推荐答案
更新2019
继续OOPS的最佳实践,@ MrTrick的答案必须是 标记为正确,尽管我的回答提供了一个被黑的解决方案,但事实并非如此 最好的方法.
Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.
使用{}
示例:
$videos{0}->id
这样,您的对象不会被破坏,并且可以轻松地遍历对象.
This way your object is not destroyed and you can easily iterate through object.
对于PHP 5.6及更低版本,请使用此
For PHP 5.6 and below use this
$videos{0}['id']
这篇关于获取PHP stdObject中的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!