使用动态名称遍历对象的属性
我试图从 twitter api 获取当前趋势(但这有点无关紧要)。
我将信息作为对象接收。在这种情况下,我需要访问的一些属性是趋势上次更新时的日期,因此我无法对属性名称进行硬编码。
这是一个例子,以防我没有很好地解释自己,我担心我没有:(
stdClass Object
(
[2011-03-09 02:45] => Array
(
[0] => stdClass Object
(
[promoted_content] =>
[events] =>
[query] => RIP Mike Starr
[name] => RIP Mike Starr
)
[1] => stdClass Object
(
[promoted_content] =>
[events] =>
[query] => Mac & Cheese
[name] => Mac & Cheese
)
注意:这不是完整的对象
I am trying to get the current trends from the twitter api (but that's sorta irrelevant).
I receive the information as an object. In this situation some of the properties that I need to access, are dates from when the trends were last updated, therefore I can't hard code the property names.
Here's an example incase I didn't explain myself well, which I fear I didn't :(
stdClass Object
(
[2011-03-09 02:45] => Array
(
[0] => stdClass Object
(
[promoted_content] =>
[events] =>
[query] => RIP Mike Starr
[name] => RIP Mike Starr
)
[1] => stdClass Object
(
[promoted_content] =>
[events] =>
[query] => Mac & Cheese
[name] => Mac & Cheese
)
Note: This is not the full object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
get_object_vars()
遍历对象的属性You can traverse an object's properties using
get_object_vars()
您是否以 JSON 格式获取此数据?如果是这样,请查看
json_decode
的第二个参数,它允许您以关联数组而不是对象的形式返回结果。这将允许您使用正常的循环结构,例如foreach
并使用array_keys
获取键。如果您没有通过 JSON 获取此数据,您可以考虑使用 Reflection 来获取对象的属性。 (编辑#2:我不确定这是否适用于 stdClass,实际上......)
Are you getting this data as JSON? If so, check out the second argument to
json_decode
, which lets you get the results back as an associative array instead of as an object. This will let you use the normal loop constructs, likeforeach
and obtain keys usingarray_keys
.If you aren't getting this data via JSON, you can consider using Reflection to grab the properties of an object. (edit #2: I'm not sure if this will work on stdClass or not, actually...)