【问题标题】:Error "Invalid argument supplied for foreach()" on my function [duplicate]我的函数上出现错误“为 foreach() 提供的参数无效”[重复]
【发布时间】:2012-10-22 16:15:09
【问题描述】:

可能重复:
Invalid argument supplied for foreach()

所以,我有这个功能:

        <?php
        function get_instagram($user_id=15203338,$count=6,$width=190,$height=190){
            $url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token=13137.f59def8.1a759775695548999504c219ce7b2ecf&count='.$count;
            // Let's create a cache
            $cache = './wp-content/themes/multiformeingegno/instagram_json/'.sha1($url).'.json';
            if(file_exists($cache) && filemtime($cache) > time() - 1000){
                // If a cache file newer than 1000 seconds exist, use that
                $jsonData = json_decode(file_get_contents($cache));
            } else {
                $jsonData = json_decode((file_get_contents($url)));
                file_put_contents($cache,json_encode($jsonData));
            }
            $result = '<div id="instagram">'.PHP_EOL;
            foreach ($jsonData->data as $key=>$value) {
                $title = (!empty($value->caption->text))?' '.$value->caption->text:'...';
                $location = (!empty($value->location->name))?' presso '.$value->location->name:null;
                $result .= "\t".'<a class="fancybox" data-fancybox-group="gallery" href="'.$value->images->standard_resolution->url.'"><img src="'.$value->images->low_resolution->url.'" alt="'.$value->caption->text.'" width="'.$width.'" height="'.$height.'" /></a>
                <div style="display: none;">'.htmlentities($title, ENT_QUOTES, "UTF-8").'<br><em style="font-size:11px">Scattata il '.htmlentities(strftime('%e %B %Y alle %R', $value->caption->created_time + 7200)).' '.htmlentities($location).' (<a target="_blank" style="color:darkgrey" rel="nofollow" href="http://maps.google.com/maps?q='.htmlentities($value->location->latitude).',+'.htmlentities($value->location->longitude).'">mappa</a>)</em></div>'.PHP_EOL;
            }
            $result .= '</div>'.PHP_EOL;
            return $result;
        }
        echo get_instagram();
        ?>

我收到很多这样的错误:FastCGI 在 stderr 中发送:“PHP 消息:PHP 警告:为 foreach() 提供的参数无效。问题所在的行是

foreach ($jsonData->data as $key=>$value) {

这有什么问题?

提前谢谢各位! :)

【问题讨论】:

  • 错误信息是描述性的——你认为的数组实际上不是。 var_dump($jsonData-&gt;data); 自己看吧
  • 嗯.. var_dump($jsonData->data);做? :) 我是一个 PHP 菜鸟,我实际上在这里和那里复制了这个函数的一部分......
  • @MultiformeIngegno 是 PHP 中最基本的调试形式。它将转储传递给它的任何内容 - 在这种情况下,$jsonData 是某个对象,而您 希望 它的 data 属性是一个数组。 var_dump() 将证明或反驳。
  • @MultiformeIngegno:“我是 PHP 菜鸟,我实际上在这里和那里复制了这个函数的一部分” --- 你的目标是什么?在这种情况下你不会学到任何东西。
  • 感谢迈克尔的解释和 zerkms 你是对的..我应该首先研究一些东西..

标签: php function foreach


【解决方案1】:

当您使用json_decode 时,您会得到一个对象。如果你想要一个数组,你可以使用json_decode 的第二个参数,它是一个用于返回对象或数组的切换。 true 给出数组。

您需要调整代码以使用新数组。

另一件可能有帮助的事情(不确定,因为我不知道对象中有什么)是将对象转换为数组(但这有点小技巧;)):

foreach ((array) $jsonData->data as $key=>$value) {

【讨论】:

    【解决方案2】:

    在你的 foreach 之前尝试以下操作:

    if(is_array($jsonData->data)){
        // Do the for each
    } else {
        // It wasn't an array so do something else
        // Like an error message or w/e
    }
    

    当您在 json 中获得的内容并不总是数组时,这很有用。

    如果假设它是一个数组,则仅将其用于调试并在 else 中执行 var_dump($jsonData-&gt;data); 以查看实际得到的结果

    【讨论】:

    • 嗯..我对 PHP 了解不多,但这似乎有点脏..?它应该做什么? :)
    • 它会检查该值是否为数组。如果您实际上假设总是得到一个数组,它可以用于测试。但是,如果你得到的并不总是一个数组,那么它就是最好的解决方案
    • 好的,该功能似乎工作正常(和以前一样)。现在我在等着看我是否仍然得到错误。 :)
    • 您遇到的错误可能是由请求中的错误引起的。所以你可能收到了一个 JSON,其中只有“错误”,这显然不是一个数组。
    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多