什么导致警告"为foreach()"提供的参数无效;在这种情况下?

时间:2015-03-17 16:58:26

标签: php foreach flickr invalid-argument

我无法掌握在这种情况下导致无效参数警告的内容。我已经看到有关于警告本身的大量信息,但是因为我是新的(今天开始使用php),即使我在论坛上阅读了很多关于此的问题,我也无法弄明白。 错误发生在for-each循环中。在我学习的时候,请非常具体地回答你的答案。

<?php
function GetWeather($city){
    $content = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=" . $city . "&units=metric");

    $data = json_decode($content, true);

    $placeinfo = '<span id="City">' . $data['name'] . ", " . $data['sys']['country'] . '</span>'
            .   "<br />"
            .   '<span id="Conditions">' . $data['weather']['0']['main'] . '</span>'
            .   "<br />"
            .   '<span id="Temperature">'  . ceil($data['main']['temp']) . " C</span>"
            .   "<br />";
    return $data ['weather']['0']['main'];

}

Function GetFlickr($city, $conditions)
{    
    $apikey = '';
    $apisecret = ''; 

    $flickrurl = "https://api.flickr.com/services/rest/?method=flickr.photos.search&tags=" . $city . "," . $conditions . "&sort=relevance&format=json&api_key=" .$apikey;
    $flickrurl .= 'per_page = 1'; 
    $result = file_get_contents($flickrurl);
    $jason = substr($result,  strlen("JasonFlickrApi(")-1);
    $flickrjson = json_decode($jason, true);       

    var_dump($flickrjson);        

    foreach ($flickrjson['photos']['photo'] as $photo) {
        $url = "http://farm" . $photo['farm'] . ".static.flickr.com/" . $photo['server'] . "/" . $photo['id'] . "_" . $photo['secret'] . "_m.jpg";
        ?>
        <img src="<?php echo $url; ?> " alt=" <?php echo $photo ['title']; ?>">
    <?php
    }
 }
 ?>

2 个答案:

答案 0 :(得分:3)

更改...

foreach ($flickrjson['photos']['photo'] as $photo) {

为...

foreach ($flickrjson['photos'] as $photo) {

<强>解释
foreach遍历数组,上面看起来就像你试图循环一个单个对象而不是一个数组。

基本上,invalid argument supplied foreach()表示您已经传递了一些不是数组或对象的内容,例如字符串,整数或null。

答案 1 :(得分:0)

如果给定的参数不是数组对象

foreach 会生成此警告
在致电foreach()

之前,您必须经常进行此项检查
if (is_array ($flickrjson['photos']['photo'])) {
    foreach ($flickrjson['photos']['photo'] as $photo) {
    // ...
    }
}else {
    // a good/must practice to log warning/error/fatal 
    // log.warn("invalid argument");
}