tags:

views:

116

answers:

3

Hello,

I am having some problem with foreach statement.Though the input to foreach statement is an array, it says

Invalid argument supplied for foreach()

and my code looks like this

foreach($res_array as $res)
     {
       foreach($res as $re)
       {
           echo $re['shortUrl'];
       }
     }

and my array looks like this

Array ( [errorCode] => 0 [errorMessage] => [results] => Array ( [http://www.telegraph.co.uk/earth/earthpicturegalleries/5966251/The-weirdest-animals-on-Planet-Earth.html?image=5] => Array ( [hash] => 2qNNV6 [shortUrl] => http://su.pr/2qNNV6 ) ) [statusCode] => OK )

I am getting that error for the second foreach. Please help me with this problem.

+5  A: 

Because not every element of your original array is itself an array. For instance, you have errorCode which is an integer, thus throwing an error.

JG
thanks for ur help
Sakura
A: 

in your example each value of the top array is also an array. It doesn't seem to be correct from your example. before performing second foreach loop, you need to check whether element is an array.

SilentGhost
thank u so much for ur help
Sakura
+1  A: 

I think you want to loop over $res_array['results'], rather than $res_array. You shouldn't need to nest your foreach loops either.

It looks like the result array contains some additional information, so you might want to do something like (untested):

$res_array = GetResultsFromSomewhere();

if ($res_array['errorCode']) {
    die("Error {$res_array['errorCode']}: {$res_array['errorMessage']}");
}

foreach ($res_array['results'] as $url => $item) {
    echo $item['shortUrl'];
}
Tom Haigh
thank u so much for ur help
Sakura