访问数组和对象

时间:2012-10-02 05:27:13

标签: arrays codeigniter object foreach

打印数据时遇到问题。在我的程序中,我获取对象中的数据并放入数组中。比如array1 [$ id] = dataobject。整个array1然后将被放入array2 ['list'],如array2 ['list'] = array1;

问题是如何获取id,name和description等数据..这是整个数组的print_r:

这实际上是数组的结果,我不知道如何访问它。我想要预约并获取名称并打印出来:

Array ( 
[list] => Array ( 
    [0] => Array ( 
        [0] => stdClass Object ( 
            [id] => 1 
            [name] => harry potter 4 
            [description] => harry potter and the goblet of fire book by j.k. rowling 
            [unit_price] => 300.99 
        ) 
    ) 
    [1] => Array (
        [0] => stdClass Object ( 
            [id] => 4
            [name] => lipton tea
            [description] => yellow label tea
            [unit_price] => 15.00 
        ) 
    ) 
    [2] => Array (
        [0] => stdClass Object (
            [id] => 9
            [name] => tisyu
            [description] => tissue twenty pieces
            [unit_price] => 20.00
        ) 
    )

) 

)

1 个答案:

答案 0 :(得分:1)

您必须访问以下内容:

foreach($array['list'] as $array_item){
    $object = $array_item[0];

    echo $object->id."<br />";
    echo $object->name."<br />";
    echo $object->description."<br />";
    echo $object->unit_price."<br />";
}

这会产生:

1
harry potter 4
harry potter and the goblet of fire book by j.k. rowling
300.99
4
lipton tea
yellow label tea
15.00
9
tisyu
tussue twenty pieces
20.00

您可以使用 - &gt;访问对象属性运营商,然后是您想要访问的财产。