/    Sign up×
Community /Pin to ProfileBookmark

How to iterate an object

Hi – I’ve consumed some data from a web service and I have it in an object. I’m used to iterating arrays, but I’m having trouble seeing how this works for objects. Here is what the object look like when I do print_r() (I added some formatting for clarity):

[code=php]stdClass Object (
[return] => Array (
[0] => stdClass Object (
[individualWinePageURL] =>
[previousTradePercentage] => 6.6364
[region] => bdxr
[tradePrice] => 1100
[transactionDate] => 2012-10-17T00:00:00.000+01:00
[unitSize] => 12x75cl
[vintage] => 1988
[wineCode] => 144
[wineName] => Lynch Bages )
[1] => stdClass Object (
[individualWinePageURL] =>
[previousTradePercentage] => 4.3478
[region] => rho
[tradePrice] => 575
[transactionDate] => 2012-10-16T00:00:00.000+01:00
[unitSize] => 12x75cl
[vintage] => 2010
[wineCode] => 317466
[wineName] => Clos Papes, CNDP )
[2] => stdClass Object (
[individualWinePageURL] =>
[previousTradePercentage] => -1.0417
[region] => bdxr
[tradePrice] => 4800
[transactionDate] => 2012-10-16T00:00:00.000+01:00
[unitSize] => 12x75cl
[vintage] => 2004
[wineCode] => 622
[wineName] => Lafite Rothschild
) ) ) [/code]

I’ve tried various kinds of loops but none of them work. Like for example (after loading the object to $results):

[code=php]foreach ( $results as $key => $value ) {

echo $results->wineName;

}[/code]

Many variations on this as I looked for examples online as well. The thing that I’m not getting is do I have to name each level of the object? ( stdClass Object – Array – stdClass Object – Key/value?) But if I do, I don’t get how to name each part. Please help! :0)

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 17.2012 — Looks like you could do:
[code=php]
foreach($results->return as $data) {
echo $data->wineName;
}
[/code]

However, a better question might be to look at how you're ending up with a bunch of stdClass objects, when maybe an array would be more appropriate, such as if the data is the result of a json_decode() and you might want to set its optional 2nd parameter to true.
Copy linkTweet thisAlerts:
@robahasauthorOct 17.2012 — That did it! Thanks for the response.
×

Success!

Help @robahas spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.3,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...