php - Why is foreach over a results object not working? -


i realize there quite few questions of nature, have not been able solve issue using other posts, hoping here may able me out.

i have object i'm getting yahoo local search api. have passed results json_decode() , saved results $yahoo_json_decoded. can data results using loop , doing following:

echo 'name: ' . $yahoo_json_decoded->resultset->result[$i]->title . '<br />' ; 

but can't seem able make foreach work:

foreach($yahoo_json_decoded->resultset $res=>$variable) {     $listingid = $yahoo_json_decoded->resultset[$res]->id ;     echo $listingid; } 

i loop data , move on, want understand why foreach isn't working.

thanks (show mercy)

kirk

the literal difference between 2 loops

the for loop in snippet iterates on array $yahoo_json_decoded->resultset->result, while foreach loop iterates on object $yahoo_json_decoded->resultset.

in other words, in for loop you're iterating on array elements expect, whereas in foreach loop in fact iterating on object properties.

a demonstration of difference

for example, given object:

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

consider difference between loop:

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

and loop:

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

the output of first loop be:

0 - apple 1 - orange 2 - lemon 

while output of second be:

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

see difference in action


Comments