milenmk
milenmk

Reputation: 544

How to access values in an array of objects

I'm struggling with extracting values from an array. print_r($offers); output is as follow:

Array
(
    [0] => Object
        (
            [id] => 41302512
            [amount] => 244
            [price] => 10.17
            [sellerId] => 1678289
            [sellerName] => stan_J23
        )
    [1] => Object
        (
            [id] => 41297403
            [amount] => 51
            [price] => 10.18
            [sellerId] => 2510426
            [sellerName] => kszonek1380
        )
    [2] => Object
        (
            [id] => 41297337
            [amount] => 581
            [price] => 10.18
            [sellerId] => 2863620
            [sellerName] => NYski
        )
)

However, echo $offers[0]['id']; doesn't work. I need to extract the values for each array node to variables i.e. $id=value_of_key_id and so on. The array has 10 nodes from 0 to 9.

Upvotes: 1

Views: 52

Answers (3)

milenmk
milenmk

Reputation: 544

Thanks to all, working code is:

foreach ($offers as $offer) {
$id = $offer->id;
$amount = $offer->amount;
$price = $offer->price;
$sellerId = $offer->sellerId;
$sellerName = $offer->sellerName;
echo "$id<br />$amount<br />$price<br />$sellerId<br />$sellerName<br /><hr /><br />";
}

Upvotes: 0

dgersting
dgersting

Reputation: 11

$offers is an array of objects, not array. You will need to access the elements via $offers[0]->id; and so on

Upvotes: 0

bozdoz
bozdoz

Reputation: 12860

Try echo $offer[0]->{'id'}.

It says it's an object, and you need to get the 'id' key in that way with objects.

See Docs: http://www.php.net/manual/en/language.types.object.php

Upvotes: 2

Related Questions