获取 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?
谢谢!
推荐答案
更新 PHP 7.4
大括号访问语法自 PHP 7.4 起已弃用
Curly brace access syntax is deprecated since PHP 7.4
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.
使用 {} 简单地迭代它
Simply iterate its using {}
示例:
$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']
相关文章