如何从php数组中获取价值?

时间:2014-05-05 13:34:37

标签: php arrays oop

抱歉,这是一个简单的问题,但对我来说很难,因为我是一名新的php开发人员。我有一个数组$ thread_template,它是动态生成的。当我使用print_r函数打印此数组时,它会给出

 BP_Messages_Thread_Template Object
(
    [current_message] => 3
    [message_count] => 4
    [message] => stdClass Object
        (
            [id] => 73 // I want to get this id.
            [thread_id] => 63
            [sender_id] => 289
            [subject] => Re: This is an anonymous message about a dino
            [message] => this message is second reply from family member.
            [date_sent] => 2014-05-05 13:25:10
            [anonymous] => 
        ) .... and so on

我希望在第6行获得ID。我正在使用

$thread_template->$message->id;

我也用过

$thread_template[message][id];

两者都不起作用。我怎样才能获得身份证?

2 个答案:

答案 0 :(得分:2)

首先,您不是在处理数组,而是使用object$thread_template),并且您正在尝试访问其中一个properties。您不需要美元符号($)来访问属性名称。

因此,假设属性为public,请使用:

$thread_template->message->id;

(如果它们不公开,你需要使用一个返回属性值的方法。不看代码,我不能告诉你是否是这样的情况,如果是这样,你用哪种方法需要使用)

正如您现在可能已经注意到的,对象$thread_template包含许多属性,包括message也是其自身的对象。 message对象也包含许多属性,包括id属性(我们正在寻找的属性)。

是否存在我应该在属性名称中使用美元符号的情况?

仅当您要调用名称保存在变量中的属性时。例如:

$propertyName = 'fooBar';
echo $myObject->$propertyName;

与:

相同
echo $myObject->fooBar;

(但这只是一个旁注,通常你不必这样做)

答案 1 :(得分:1)

它不是数组,它是一个对象,请尝试:

$thread_template->message->id