简体   繁体   English

php-如何从数组对象获取值

[英]php - how to get value from an array object

I use php code and I have a problem with getting value of an array object. 我使用php代码,但在获取数组对象的值时遇到问题。 When I use var_dump($arr) , I get this (the code below is formatted for better readability): 当我使用var_dump($arr) ,我得到了(以下代码经过格式化以提高可读性):

object(League\OAuth2\Client\Provider\GoogleUser)#5 (1) {
    ["response":protected]=> array(5) {
        ["emails"]=> array(1) {
            [0]=> array(1) {
                ["value"]=> string(21) "thienlam129@gmail.com"
            }
        }
        ["id"]=> string(21) "115281634466837725533"
        ["displayName"]=> string(18) "thiên lâm trần"
        ["name"]=> array(2) {
            ["familyName"]=> string(6) "trần"
            ["givenName"]=> string(11) "thiên lâm"
        }
        ["image"]=> array(1) {
            ["url"]=> string(98) "https://lh3.googleusercontent.com/-SpWfKGTcQt8/AAAAAAAAAAI/AAAAAAAAAB8/IlGQQnvy7so/photo.jpg?sz=50"
        }
    }
}

Please, tell me how to get emails value. 请告诉我如何获得电子邮件的价值。

The main reason you're facing this problem is probably because the object is not an array at all. 您面临此问题的主要原因可能是因为该对象根本不是数组。

As mentioned in the comments, the GoogleUser object has a public getEmail method which you can use to retrieve the email address. 如评论中所述, GoogleUser对象具有公共的getEmail方法,您可以使用该方法来检索电子邮件地址。

You can use it like this: 您可以像这样使用它:

$email = $googleUser->getEmail();

(In the above code sample I took the liberty of calling it a $googleUser rather than an $arr because it's not an arr but a google user) (在上面的代码示例中,我$googleUser将其称为$googleUser而不是$arr因为它不是arr而是Google用户)

You could cast the object as an array as such: 您可以像这样将对象转换为数组:

var_dump((array) $object);

Or 要么

$array = (array) $object;

And access all its properties but you might have to array walk and filter the name of the class out. 并访问其所有属性,但是您可能必须对walk进行数组并过滤掉类的名称。

But this is a hack and an example of bad practise. 但这是骇客行为,也是不良作法的一个例子。 Accessing protected properties by its methods is the way to go or else request json object instead, if possible. 通过它的方法访问受保护的属性是一种方法,或者如果可能的话,可以请求json对象。

Naturally, you would say 自然,你会说

$object = (object) $inputObject;
$value = (string) $object->getValue();

Or 要么

$value = (array) $object->getArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM