accessing array and objects

2019-06-14 19:20发布

问题:

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.