按索引号(而不是名称)返回 PHP 对象
目标:按数字从 PHP 对象中检索数据元素。
这是对象的 print_r($data) :
stdClass Object
(
[0] => stdClass Object
(
[TheKey] => 1456
[ThingName] => Malibu
[ThingID] => 7037
[MemberOf] => California
[ListID] => 7035
[UserID] => 157
[UserName] => John Doe
)
)
我不知道如何从中提取值。这只是多记录对象的一条记录,应该按 ID 而不是名称。
以下是一些失败的尝试来说明目标是什么:
echo $data -> 0 -> UserName;
echo $data[0] -> UserName;
Goal: retrieve an element of data from within a PHP object by number.
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
)
)
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通常,PHP 变量名不能以数字开头。您无法将
$data
作为数组进行访问,因为stdClass
未实现ArrayAccess
— 它只是一个普通的基类。但是,在这种情况下,您可以尝试通过数字名称访问对象属性,如下所示:
我能想到 Spudley 的答案会导致错误的唯一原因是因为您正在运行 PHP 4,它不支持使用 < code>foreach 来迭代对象。
Normally, PHP variable names can't start with a digit. You can't access
$data
as an array either asstdClass
does not implementArrayAccess
— 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:
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.BoltClock 建议使用“$data->{'0'}->UserName”显然不再适用于 PHP 5。
我遇到了同样的问题,我发现 current() 可以像这样获取编号的类元素...
或者,如果这不起作用(取决于对象),您可能需要执行另一个 current() 调用,如下所示:
BoltClock's suggestion to use "$data->{'0'}->UserName" apparently no longer works with PHP 5.
I had the same problem and I found that current() will work to get that numbered class element like this...
Or if that doesn't work (depending on the object) you may need to do another current() call like this:
这适用于 PHP5+
或
或按照 @orrd 的建议
this works for PHP5+
or
or as suggested by @orrd
您尝试过 foreach() 循环吗?这应该为您提供所有可访问的元素,并且
它返回的键可能会为您提供有关如何直接访问它们的更好线索。
Have you tried a
foreach()
loop? That should give you all the accessible elements, and thekeys it returns may give you a better clue as to how to access them directly.
试试这个:根据手册,对象不应该以这种方式使用。如果这是必须的,此页面上的注释确实提供了一种解决方法-有给你的。如果您只是将对象用于属性(而不是行为),您也可以简单地依赖数组。
try this:According to the manual, objects are not meant to be used that way. The comments on this page do provide a way around if that's a must-have for you. You could also simply rely on arrays if you are just using the object for properties (and not behaviours).