获取 PHP std 中的第一个元素对象

2022-08-30 08:24:36

我有一个对象(存储为$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 呢?可能吗?

谢谢!


答案 1

array() 和 stdClass 对象都可以使用 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

答案 2

更新 PHP 7.4

自 PHP 7.4 起,大括号访问语法已弃用

更新 2019

转到OOPS的最佳实践,@MrTrick的答案必须标记为正确,尽管我的答案提供了一个被黑客入侵的解决方案,但它不是最好的方法。

只需使用 {} 迭代它

例:

$videos{0}->id

这样,您的对象就不会被破坏,您可以轻松地循环访问对象。

对于 PHP 5.6 及更低版本,请使用此

$videos{0}['id']

推荐