我有一个对象$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
,但这也无效。
答案 0 :(得分:3)
答案 1 :(得分:1)
$ images不是数组,它是StdClass类型的对象(标准类实际上是一个虚拟类)。要访问类成员,您必须使用格式
$object->membername
不幸的是,0不是有效的成员名称。因此,您无法使用$ images-> 0。解决方法是使用格式
$images->{"0"}
以下内容也适用(取决于您的PHP版本)
$a = 0;
$images->$a;
答案 2 :(得分:0)
尝试
$obj = $images["0"];
或
$key = 0;
$obj = $images[ $key ];
答案 3 :(得分:0)
试试这个:
$a = $image->0;
$id = $a->id
答案 4 :(得分:0)
使用此方法,因为图像也是一个对象,其中一个也是对象
$images->{0}->id;
答案 5 :(得分:0)
尝试 $图像 - > 0→ID 这可能适用于您的代码