【问题标题】:Parsing Json Response from api call - foreach error解析来自 api 调用的 Json 响应 - foreach 错误
【发布时间】:2014-11-20 05:30:47
【问题描述】:

我正在使用 instagram api。这个问题不是Instagram 特定的,而是更多关于解析 api 调用返回的响应。该 api 适用于分页。通过一些研究,我找到了一种方法来获取大量结果并避免分页。我在解析 json 文件时遇到问题。在foreach 循环中,我尝试解析,但出现此错误:Invalid argument supplied for foreach()。如何在foreach 循环中正确解析 json 文件值?

LINK 到文章中,如果不熟悉 api 则解释该过程

问题在这里:尝试解析foreach loop - 包括一个测试访问令牌。这可以在任何地方进行测试

$get_media_url = 'https://api.instagram.com/v1/tags/nataliguatemipoa/media/recent?access_token=6678174.467ede5.205a03ebc4b74d4082823781c3149575';

$media = getResults($get_media_url); //Look Below to find function details
foreach($media['data'] as $insta){
        $source_id = $insta['id'];
    }

这是 Instagram 响应的示例,

Array
(
    [0] => stdClass Object
        (
            [pagination] => stdClass Object
                (
                    [next_min_id] => 1407287255810188
                    [deprecation_warning] => next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead
                    [min_tag_id] => 1407287255810188
                )

            [meta] => stdClass Object
                (
                    [code] => 200
                )

            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [attribution] => 
                            [tags] => Array
                                (
                                    [0] => muff
                                    [1] => hairstylist
                                )
//Cut the rest for example purposes

调用 api

function __apiCall($url, $post_parameters = FALSE) {

        // Initialize the cURL session
        $curl_session = curl_init();

        // Set the URL of api call
        curl_setopt($curl_session, CURLOPT_URL, $url);

        // If there are post fields add them to the call
        if($post_parameters !== FALSE) {
            curl_setopt ($curl_session, CURLOPT_POSTFIELDS, $post_parameters);
        }

        // Return the curl results to a variable
        curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);

        // Execute the cURL session
        $contents = curl_exec ($curl_session);

        // Close cURL session
        curl_close ($curl_session);

        // Return the response
        return  json_decode($contents);
    }

获取所有分页结果

function getResults($url){

        $gotAllResults = false;
        $results = array();

        while(!$gotAllResults) {
        $result = $this->__apiCall($url);
        $results[] = $result;

        if (!property_exists($result->pagination, 'next_url')) {
            $gotAllResults = true;
        } else {
            $url = $result->pagination->next_url;
        }
    }

    return $results;

    }

【问题讨论】:

    标签: php json foreach


    【解决方案1】:

    您正在使用 php stdClass 对象。您当前的 for 循环适用于常规 array 但不适用于 php stdClass。

    如果返回的 API 响应格式为 php stdClass 对象,则为了能够访问这些值,请更改为以下内容:

    foreach($media[0]->data as $insta){
        $source_id = $insta->id;
    }
    

    如果返回的 API 响应为正则数组,则保持原样:

    foreach($media['data'] as $insta){
            $source_id = $insta['id'];
        }
    

    现在您可以更改为您想要的格式了。默认情况下,它似乎返回一个 php stdClass。要转换为普通的array,请将您的函数__apiCall 中的以下内容更改为:

    return  json_decode($contents, true);
    

    【讨论】:

    • 是的,这很完美!谢谢你的解释。
    【解决方案2】:

    $insta 是一个对象,而不是一个数组。你应该这样引用:

    foreach($media[data] as $insta){
        $source_id = $insta->id;
    }
    

    对象被引用为->。数组被引用为[]

    这里有两个选项之一,您可以尝试将其引用为第一个:

    foreach($media['data'] as $insta){
        $source_id = $insta->id;
    }
    

    或者你可以尝试作为一个对象

    foreach($media->data as $insta){
        $source_id = $insta->id;
    }
    

    【讨论】:

    • 好的,它仍然给出Invalid argument supplied for foreach()的相同错误
    • print_r($media) 提供什么?
    • 但是data 在里面吗?
    • 是的data 存在
    • 显示print_r($media) 会很棒,因此我们可以帮助您调试
    【解决方案3】:

    尝试将其转换为 array -

    foreach((array)$media[0]['data'] as $insta) {
       $source_id = $insta->id;
    }
    

    【讨论】:

    • 好的,所以错误消失了,但没有值被放置在 foreach 循环中。它给出了这个错误Notice: Undefined index: data in /index.php on line 226
    • var_dump($media) 并添加看看你得到了什么或显示它。
    • array(1) { [0]=> object(stdClass)#3 (3) { ["pagination"]=> object(stdClass)#4 (3) { ["next_min_id"]=> string(16) "1407287255810188" ["deprecation_warning"]=> string(94) "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead" ["min_tag_id"]=> string(16) "1407287255810188" } ["meta"]=> object(stdClass)#5 (1) { ["code"]=> int(200) } ["data"]=> array(3) { [0]=> object(stdClass)#6 (15)
    • 它会产生这个错误Cannot use object of type stdClass as array
    • 它来了是因为$insta 是一个对象。如果$insta 在下一级有id,那么您可以再次访问它,否则必须再次添加循环。更新答案。
    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 2020-08-26
    相关资源
    最近更新 更多