php 如何从对象中的数组中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7933029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:39:23  来源:igfitidea点击:

How to get data from array in object

phparraysobject

提问by Antoon Cusell

I can't seem to get specific data from an array inside an object.

我似乎无法从对象内的数组中获取特定数据。

$this->fields->adresgets the address correctly, but i can't get a level deeper.

$this->fields->adres正确获取地址,但我无法更深入。

I've tried:

我试过了:

$this->fields->province
$this->fields->province->0
$this->fields->province[0]

And: (edit)

和:(编辑)

$this->fields["province"][0]
$this->fields['province'][0]
$this->data->fields['province'][0]

But it does not return anything while it should return "Flevoland".

但是它不会返回任何东西,而它应该返回“Flevoland”。

First part of the object print_r($this, TRUE) below:

对象 print_r($this, TRUE) 的第一部分如下:

RSMembershipModelSubscribe Object
(
    [_id] => 2
    [_extras] => Array
        (
        )

    [_data] => stdClass Object
        (
            [username] => testzz
            [name] => testzz
            [email] => [email protected]
            [fields] => Array
                (
                    [province] => Array
                        (
                            [0] => Flevoland
                        )

                    [plaats] => tesdt
                    [adres] => test

回答by Gergely Lukacsy

You can also use type casting.

您还可以使用类型转换。

$fields = (array) $this->data->fields;
echo $fields['province'][0];

回答by Damien Pirsy

As you can see by your output, object members are likely to be private (if you follow conventions, anyway you must prepend an underscore while calling them), so you're calling them the wrong way; This code works:

正如您在输出中看到的那样,对象成员可能是私有的(如果您遵循约定,无论如何您必须在调用它们时添加下划线),因此您以错误的方式调用它们;此代码有效:

$this->_data->fields['province'][0];

You can see it in action here; I created a similar object, and using

你可以在这里看到它的实际效果;我创建了一个类似的对象,并使用

$membership = new RSMembershipModelSubscribe();
echo $membership->_data->fields['province'][0];

outputs "Flevoland" as expected.

按预期输出“Flevoland”。

回答by r15habh

$this->_data->fields['province'][0]

回答by Rene Pot

As fields is already an array, try this:

由于字段已经是一个数组,请尝试以下操作:

$this->fields['province'][0]

This assuming the [_data] object is $this.

这假设 [_data] 对象是$this.

回答by Whetstone

Fields and province are both arrays, you should be trying $this->fields["province"][0]

字段和省都是数组,您应该尝试$this->fields["province"][0]