为什么我收到错误消息“无法使用 stdClass 类型的对象作为数组”


Why am I getting error message "Cannot use object of type stdClass as array"?

我有一个对象$images看起来像这样:

stdClass Object
(
    [0] => stdClass Object
        (
            [id] => 125
            [title] => 131301
            [file_name] => 131301
            [file_ext] => jpg
            [dir] => Adventure/
            [fk_gallery_id] => 1
        )
    [1] => stdClass Object
        (
            [id] => 126
            [title] => 181301
            [file_name] => 181301
            [file_ext] => jpg
            [dir] => Adventure/
            [fk_gallery_id] => 1
        )
);

现在我想获取对象中的第一个元素:

$obj = $images[0]。

这给了我错误:

Fatal error: Cannot use object of type stdClass as array

谁能告诉我为什么这不起作用?

我也尝试过$images[0]->id,但这也不起作用。

它们是类成员,因此您需要像这样访问它们:

$obj = $images->{0};

请参见:变量变量。

$images不

是一个数组,它是一个 StdClass 类型的对象(标准类实际上是一个虚拟类)。要访问类成员,您必须使用格式

$object->membername

遗憾的是,0 不是有效的成员名称。因此,您不能使用 $images->0。解决方法是使用格式

$images->{"0"}

以下内容也可以工作(取决于您的 PHP 版本)

$a = 0;
$images->$a;

尝试

$obj = $images["0"];

$key = 0;
$obj = $images[ $key ];

使用它,因为图像也是一个对象,里面也是对象

$images->{0}->id;

试试这个:

$a = $image->0;
$id = $a->id

尝试$image->0->ID这可能适用于您的代码