0

I'm trying to retrieve data from a JSON object that looks like this:

stdClass Object
(
[query] => stdClass Object
    (
        [results] => stdClass Object
            (
                [quote] => Array
                    (
                        [0] => stdClass Object
                            (
                                [foo] => bar
                            )
                        [1] => stdClass Object
                            (
                                [foo] => blah
                            )

I created the object like so:

$json = curl_exec($session);
$stock_data = json_decode($json);

I have been reading several posts on how to do this (This one was extremely useful) but I am still stuck. I know I need to iterate over the data, but I'm not exactly sure what the foreach statements would look like (ie the depth of them, so to speak). I realize that this should be relatively simple, but I can't wrap my head around it at the moment (that's what being evacuated does to you). Any help would be much appreciated!

EDIT: After thinking about it a while, this is what I came up with:

foreach( $stock_data->query->results as $quote) {
           foreach ($quote as $entry) {
                print $entry->{'foo'} ;
            }
       }

This will then successfully print both bar and blah

Community
  • 1
  • 1
thomascirca
  • 893
  • 4
  • 14
  • 30
  • 1
    Which level do you want to iterate through? It'll fundamentally be a mix of PHP arrays and objects e.g. `echo $object->query->results->quote[0]->foo` – Pekka Aug 27 '11 at 20:23
  • I wanted to iterate through each object within quote. I managed to figure it out though! – thomascirca Aug 27 '11 at 20:39

2 Answers2

2
$quotes = $stock_data->query->results->quote;
foreach ($quotes as $q)
{
  echo $q->foo;
}
Andrei Bozantan
  • 3,781
  • 2
  • 30
  • 40
1
foreach( $stock_data->query->results as $quote) {
       foreach ($quote as $entry) {
            print $entry->{'foo'} ;
        }
   }
thomascirca
  • 893
  • 4
  • 14
  • 30