如何获取数组的对象值

时间:2013-10-03 16:37:24

标签: php arrays arrayobject

我是php的新手,我正试图从twitter api阅读文字描述。我的数组看起来像:

Array
(
    [0] => stdClass Object
        (
            [created_at] => Thu Oct 03 14:50:55 +0000 2013
            [id] => 3.85778998506E+17
            [id_str] => 385778998506033154
            [text] => We tested live-tweeting with @MLB to see if teams could boost follower engagement and their Twitter audience: https://t.co/XPhHmVDNxJ
            [source] => TweetDeck
            [truncated] => 
            [in_reply_to_status_id] => 
            [in_reply_to_status_id_str] => 
            [in_reply_to_user_id] => 
            [in_reply_to_user_id_str] => 
            [in_reply_to_screen_name] => 
            [user] => stdClass Object
                (
                    [id] => 783214
                    [id_str] => 783214
                    [name] => Twitter
                    [screen_name] => twitter
                    [location] => San Francisco, CA
                    [description] => Your official source for news, updates and tips from Twitter, Inc.
                    [url] => http://t.co/5iRhy7wTgu
                    [entities] => stdClass Object

我试着这样读,但不能打印任何echo $tweets->text;

2 个答案:

答案 0 :(得分:2)

有一个包含该对象的外部数组。数组访问是通过括号完成的,因此您可以通过$tweets[0]访问第0个元素。现在您拥有了该对象,您可以访问其属性。总之,这将是$tweets[0]->text。要获取用户值,您可以使用$tweets[0]->user->description,例如。

如果返回了多条推文,您可以使用$tweets[1]等来访问其他推文值。你也可以迭代这些。

foreach ($tweets as $tweet) {
    echo $tweet->text;
}

答案 1 :(得分:2)

试试这个:

echo $tweets[0]->text;
echo $tweets[0]->user->description;

我希望这会对你有所帮助:)。