accessing array and objects

社会主义新天地 提交于 2020-01-03 06:39:08

问题


I have a problem with printing my data. In my program, i get the data which was in object and put in an array. say array1[$id] = dataobject. the whole array1 then will be put to array2['list'] like array2['list'] = array1;

the problem is how do i get the data such as the id, name and description.. here's the print_r of the whole array:

this is actually the result of the array, i am not sure how to access this. i want to foreach and get the name and print them:

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:


You would have to access them something like the following:

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 />";
}

This would yield:

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

You can access an objects properties using the -> operator, followed by the property you wish to access.



来源:https://stackoverflow.com/questions/12684989/accessing-array-and-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!