获取 PHP stdObject 中的第一个元素

新手上路,请多包涵

我有一个看起来像这样的对象(存储为 $videos)

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

  etc...

我想只获取第一个元素的 ID,而不必遍历它。

如果它是一个数组,我会这样做:

 $videos[0]['id']

它曾经这样工作:

 $videos[0]->id

但是现在我在上面显示的行上收到错误“不能使用 stdClass 类型的对象作为数组…”。可能是由于 PHP 升级。

那么如何在不循环的情况下获得第一个 ID 呢?可能吗?

谢谢!

原文由 Drew Baker 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 557
2 个回答

更新 PHP 7.4

自 PHP 7.4 起不推荐使用花括号访问语法

2019 年更新

继续讨论 OOPS 的最佳实践,@MrTrick 的答案必须标记为正确,尽管我的答案提供了一个被黑的解决方案,它不是最好的方法。

只需使用 {} 对其进行迭代

例子:

 $videos{0}->id

这样您的对象就不会被破坏,您可以轻松地遍历对象。

对于 PHP 5.6 及以下版本,请使用此

$videos{0}['id']

原文由 Clain Dsilva 发布,翻译遵循 CC BY-SA 4.0 许可协议

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() 功能。

所以,如果你的对象看起来像

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

然后你可以做;

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

如果您出于某种原因需要密钥,您可以这样做;

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

希望这对你有用。 :-) 在 PHP 5.4 上,即使在超严格模式下也没有错误


2022 年更新:

在 PHP 7.4 之后,不推荐在对象上使用 current()end() 等函数。

在较新版本的 PHP 中,使用 ArrayIterator 类:

 $objIterator = new ArrayIterator($obj);

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

$key = $objIterator->key(); // and gets the key

原文由 MrTrick 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题