无法从数组中获取值

时间:2014-04-03 07:52:58

标签: php arrays

这是一个数组,我想从中提取值[_answer:protected]和[_correct:protected]

Array
(
    [0] => Model_AnswerTypes Object
        (
            [_answer:protected] => True
            [_html:protected] => 
            [_points:protected] => 1
            [_correct:protected] => 1
            [_sortString:protected] => 
            [_sortStringHtml:protected] => 
            [_mapper:protected] => 
        )

    [1] => Model_AnswerTypes Object
        (
            [_answer:protected] => False
            [_html:protected] => 
            [_points:protected] => 1
            [_correct:protected] => 
            [_sortString:protected] => 
            [_sortStringHtml:protected] => 
            [_mapper:protected] => 
        )
)

我在用什么

$key = '_answer:protected';
foreach ($array as $data)
    {
        echo $data[0]->$key;
    }

从此

中获取空白数组

非常感谢任何帮助

3 个答案:

答案 0 :(得分:2)

假设您对模型类有点了解,我认为以下可能是您想要的。

foreach ($array as $data)
{
    echo $data->answer; //(assumes Model_AnswerTypes::_get($name) is defined)
}

如果不起作用,请尝试

foreach ($array as $data)
{
    echo $data->getAnswer(); // assumes getter/setter pattern
}

答案 1 :(得分:0)

$key = '_answer:protected';
foreach ($array as $data)
{
    echo $data->$key; // The 0 is not needful because you make a foreach :)
} 

答案 2 :(得分:0)

你有一个对象数组,而不是直接值。

由于要读取的Model_AnswerTypes对象的值受到保护,因此需要使用方法来获取它(或者类需要使用__get()魔术方法)。

通常的方法是

$data->getAnswer();

$data->answer; //if the __get() method is implemented, a more unusual  form would be $data->_answer