Reputation: 279
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.
Upvotes: 0
Views: 553
Reputation: 5695
You have an array not all its element are array, so you have first to check first each element if it is an array or not then fetch it.
<?php
foreach($res_array as $res)
{
if(is_array($res))
foreach($res as $re)
{
echo $re['shortUrl'];
}
}
?>
Upvotes: 0
Reputation: 57815
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'];
}
Upvotes: 1
Reputation: 319551
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.
Upvotes: 0
Reputation: 91299
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.
Upvotes: 5