php - 获取 PHP stdObject 中的第一个元素

标签 php object multidimensional-array

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

谢谢!

最佳答案

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

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

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

关于php - 获取 PHP stdObject 中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474446/

相关文章:

javascript - 我应该如何在这个多维数组中将名称加粗?

javascript - 糖果粉碎游戏逻辑

php - 创建模型方法以从另一个模型获取数据

php - (Yii)CDbCommand执行SQL语句失败: SQLSTATE[42000]: Syntax error or access violation:

android - 如何在 SharedPreferences 中存储 ArrayList<HashMap<String, String>> ?

python - 如何知道数组和字典等python对象的字节大小? - 简单的方法

javascript - 按两个键对对象数组进行排序和分组,并使用新键创建分组项数组

c# - 如何仅在二维数组的边缘选择点

php - Yii - 如何从另一个模型获取数据

c++ - cocos2d-x:来自另一个类的 CRUD 二维数组