0

我试图根据一些 URL 参数从 Instagram 获取 JSON,然后对 JSON 进行解码,然后将所需的对象编码为我自己的 JSON 格式。虽然我知道这听起来有点荒谬,但这是必需的。我唯一的问题是,由于某种原因,它不会对 JSON 的每个部分进行编码,它只适用于一个项目。代码如下。

<?php

function instagram($count=16){

$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];


    $url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;

        $jsonData = json_decode((file_get_contents($url)));

$jsonData = json_decode((file_get_contents($url)));
    foreach ($jsonData->data as $key=>$value) {

            $response = array();
            $response["data"] = array();
            $data = array();
            $data["createdtime"] = $value->caption->created_time;
            $data["username"] = $value->caption->from->username;
            $data["profileimage"] = $value->caption->from->profile_picture;
            $data["caption"] = $value->caption->text;
            $data["postimage"] = $value->images->standard_resolution->url;

            array_push($response["data"], $data);
            $result = json_encode($response); 

    }

    return $result;
}

echo instagram();
?>

如果我这样做,它将适用于 JSON 的每个部分:

    $result .= '<li> 
                      '.$value->caption->from->username.'<br/>
                      '.$value->caption->from->profile_picture.'<br/>
                      '.$value->caption->text.'<br/>
                      '.$value->images->standard_resolution->url.'<br/>
                      '.$value->caption->created_time.'<br/>
                      </li>';

我觉得我已经在阵列的某个地方出现了问题,但是我并不完全确定。

4

1 回答 1

1

如果我们将 $response["data"] 和 $result 变量移出 foreach 会怎样?

你试过这个吗?

$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {            

        $data = array();
        $data["createdtime"] = $value->caption->created_time;
        $data["username"] = $value->caption->from->username;
        $data["profileimage"] = $value->caption->from->profile_picture;
        $data["caption"] = $value->caption->text;
        $data["postimage"] = $value->images->standard_resolution->url;

        array_push($response["data"], $data);
}
$result = json_encode($response); 
return $result;
于 2013-08-01T04:42:21.723 回答