Why is foreach over a results object not working?

foreach, object, php, yahoo-api

Solution

The literal difference between the two loops

The `for` loop in your snippet iterates over the array `$yahoo_json_decoded->ResultSet->Result`, while the `foreach` loop iterates over the object `$yahoo_json_decoded->ResultSet`.

In other words, in the `for` loop you're iterating over the array elements as you expect, whereas in the `foreach` loop you are in fact iterating over the object properties.

A demonstration of the difference

For example, given this object:

$json = json_encode(array('result'=>array('apple','orange','lemon')));
$obj  = json_decode($json);

consider the difference between this loop:

for ($i=0; $i < count($obj->result); $i++) :
    echo $i.' - '.$obj->result[$i].' ';
endfor;

and this loop:

foreach ($obj as $key=>$val) :
    echo $key.' - ';
    var_dump($val);
endforeach;

The output of the first loop will be:

0 - apple 1 - orange 2 - lemon

While the output of the second will be:

result - array(3) { [0]=> string(5) "apple" [1]=> string(6) "orange" [2]=> string(5) "lemon" }

See the difference in action

Problem

I realize there are quite a few questions of this nature, but I have not been able to solve my issue using the other posts, so I was hoping someone here may be able to help me out. I have an object I'm getting back from Yahoo local search API. I have passed the results into `json_decode()` and saved the results to `$yahoo_json_decoded`. I can get data from the results using a for loop and doing the following: ``` echo 'Name: ' . $yahoo_json_decoded->ResultSet->Result[$i]->Title . '<br />' ; ``` But I can't seem to be able to make the foreach work: ``` foreach($yahoo_json_decoded->ResultSet as $res=>$variable) { $listingID = $yahoo_json_decoded->ResultSet[$res]->id ; echo $listingID; } ``` I could just loop the data and move on, but I really want to understand why the `foreach` isn't working. Thanks (show mercy) Kirk

Original source