在php中获取stdObject的值

时间:2014-06-10 14:34:26

标签: php api stdclass

我正在使用API​​来获取一些值。当我打印我的变量从api返回一个数组时,它返回stdObject Class

这是我请求数据的方式:

$graphObject = (new FacebookRequest( $session, 'GET', '/me?fields=id,first_name,last_name,tagged_places' ))->execute()->getGraphObject()->asArray();

这就是我打印它的方式:

echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>'; 

这就是它的回报:

    Array
(
    [id] => 111111
    [first_name] => Bob
    [last_name] => Stevensen
    [tagged_places] => stdClass Object
        (
            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 111111
                            [created_time] => 1905-01-01T08:00:00+0000
                            [place] => stdClass Object
                                (
                                    [id] => 1111111
                                    [location] => stdClass Object
                                        (
                                            [latitude] => 36.1313
                                            [longitude] => -95.9373
                                        )

                                    [name] => Tulsa, Oklahoma
                                )

                        )

                    [1] => stdClass Object
                        (
                            [id] => 11111
                            [created_time] => 2014-05-30T21:41:11+0000
                            [place] => stdClass Object
                                (
                                    [id] => 111111
                                    [location] => stdClass Object
                                        (
                                            [city] => Okmulgee
                                            [country] => United States
                                            [latitude] => 35.623012460758
                                            [longitude] => -95.972782756346
                                            [state] => OK
                                            [street] => 104 S Morton Ave
                                            [zip] => 74447-5022
                                        )

                                    [name] => Ike's Downtown Pub & Eatery
                                )

                        )

我找到了一些这样的例子,说明从这个类对象中获取值的方法就是这样,

echo $graphObject->{'$STDCLASS'}->{'$FIELD I'M TRYING TO GET'};

我正在交换这些值,试图弄清楚对象名称是什么,但是我收到了这个错误:

Notice: Trying to get property of non-object in /file/path

stdClass Object获取值的正确方法是什么?我想也许我只是不理解Object的名称是否可以从我在此处发布的代码中辨别出来?< / p>

1 个答案:

答案 0 :(得分:0)

该对象包含一个名为Data的数组,您可以访问:

foreach ($graphObject->data as $data) {
    echo $data->id
}

这会获取对象,并且应该可以直接访问

虽然第二个想法..你可能还需要尝试echo $ data ['id'];因为它不再是一个对象..

如果那样有效..试试:

$info = json_decode($graphObject,true);

并查看您是否可以更轻松地使用$ info变量。