2018-09-18 15:48 阅读 306

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

I use php code and I have a problem with getting value of an array object. When I use var_dump($arr), I get this (the code below is formatted for better readability):

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongmu3187 dongmu3187 2018-09-18 18:56

    You could cast the object as an array as such:

    var_dump((array) $object);


    $array = (array) $object;

    And access all its properties but you might have to array walk and filter the name of the class out.

    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.

    Naturally, you would say

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


    $value = (array) $object->getArray();
    点赞 评论 复制链接分享
  • doushi1960 doushi1960 2018-09-18 18:46

    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.

    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)

    点赞 评论 复制链接分享