在PHP中显示Std Class的值

时间:2013-02-25 18:15:13

标签: php

全部, 我有以下代码来从Tumblr获取一些帖子:

$baseHostname = "name.tumblr.com";
$tumblrConsumerKey = "asfd"; # use your own consumer key here
$humblr = new Humblr($baseHostname, $tumblrConsumerKey);

$post = $humblr->getPosts(array('limit' => 1));
print_r($post);

这很好用,给我一个类似的结果:

Array ( 
    [0] => stdClass Object ( 
        [blog_name] => name 
        [id] => 43993 
        [post_url] => http://name.tumblr.com/post/43993/
        [slug] => slug 
        [type] => video 
        [date] => 2013-02-25 18:00:25 GMT 
        [timestamp] => 1361815225 
        [state] => published 
        [format] => html )

我尝试显示一些像这样的值:

echo "The blog name is: ".$post->blog_name;
echo $post->id;

但是,它是空白的。如何显示这些值?

由于

2 个答案:

答案 0 :(得分:1)

我看到它是一个数组,所以你可以尝试:

echo $post[0]->blog_name;

答案 1 :(得分:1)

首先,启用error reporting

// error reporting for development environment
error_reporting(-1);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);

正如@Zlatan指出的那样,它是stdClass的数组

启用错误报告后,您将收到错误通知"注意:尝试获取此代码的非对象属性..."

echo "The blog name is: ".$post->blog_name;
echo $post->id;

因为您正在尝试访问非对象。

你可以通过它的数组索引访问对象来修复它:

echo "The blog name is: ".$post[0]->blog_name;
echo $post[0]->id;

假设$posts

Array
(
    [0] => stdClass Object
        (
            [blog_name] => blog1
            [id] => 10234
            [post_url] => http://name.tumblr.com/post/43993/
            [slug] => slug
            [type] => video1
            [date] => 2013-02-25 18:00:25 GMT
            [timestamp] => 1361815225
            [state] => published
            [format] => html
        )

    [1] => stdClass Object
        (
            [blog_name] => blog2
            [id] => 20234
            [post_url] => http://name.tumblr.com/post/43993/
            [slug] => slug1
            [type] => video
            [date] => 2013-02-25 18:00:25 GMT
            [timestamp] => 1361815225
            [state] => published
            [format] => html
        )

)

按数组索引访问对象:

echo "The blog name is: ".$post[0]->blog_name;
echo $post[0]->id;
echo "The blog name is: ".$post[1]->blog_name;
echo $post[1]->id;

// prints
// The blog name is: blog1
// 10234
// The blog name is: blog2
// 20234

如果你想循环帖子:

foreach ($posts as $post) {
    echo "The blog name is: ".$post->blog_name;
    echo $post->id;
}

// prints
// The blog name is: blog1
// 10234
// The blog name is: blog2
// 20234

资源