按索引号(不是名称)返回 PHP 对象 [英] Return PHP object by index number (not name)
问题描述
目标:通过数字从 PHP 对象中检索数据元素.
Goal: retrieve an element of data from within a PHP object by number.
这是对象的print_r($data):
This is the print_r($data) of the object:
stdClass Object
(
[0] => stdClass Object
(
[TheKey] => 1456
[ThingName] => Malibu
[ThingID] => 7037
[MemberOf] => California
[ListID] => 7035
[UserID] => 157
[UserName] => John Doe
)
)
我不知道如何从中提取一个值.这只是一个多记录对象的一个记录,应该是id而不是名字.
I can't figure out how to pull a value out of it. This is only one record of a multi-record object that should be by id rather than a name.
这些是一些失败的尝试来说明目标是什么:
These are some failed attempts to illustrate what the goal is:
echo $data -> 0 -> UserName;
echo $data[0] -> UserName;
推荐答案
通常,PHP 变量名称不能以数字开头.您不能将 $data
作为数组访问,因为 stdClass
没有实现 ArrayAccess
— 它只是一个普通的基类.
Normally, PHP variable names can't start with a digit. You can't access $data
as an array either as stdClass
does not implement ArrayAccess
— it's just a normal base class.
但是,在这种情况下,您可以尝试通过数字名称访问对象属性,如下所示:
However, in cases like this you can try accessing the object attribute by its numeric name like so:
echo $data->{'0'}->UserName;
我能想到为什么 Spudley 的答案会导致错误的唯一原因是因为您正在运行 PHP 4,它不支持使用 foreach
来迭代对象.
The only reason I can think of why Spudley's answer would cause an error is because you're running PHP 4, which doesn't support using foreach
to iterate objects.
这篇关于按索引号(不是名称)返回 PHP 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!