通过索引号(不是名称)返回PHP对象 [英] Return PHP object by index number (not name)

查看:60
本文介绍了通过索引号(不是名称)返回PHP对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:按编号从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆