1

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.

2
  • 4
    [0] is an object, not an array. So do $offers[0]->id Commented Dec 8, 2013 at 9:48
  • 1
    That's because $offers[0] is an Object, not an array. Use $offers[0]->id Commented Dec 8, 2013 at 9:48

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Why ->{'id'} and not just ->id?
I've kind of forced myself to always use curly brackets, so that it always works; but you're right: it's unnecessary in this case. @pduersteler
echo $offers[0]->id; works. The only left is how to loop from 0 to 9.
just hadn't seen that syntax before, so I had to ask. Thanks!
0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.