获取、解码和重新编码JSON


Fetch, Decode and Re-encode JSON

我正试图根据一些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>';

我觉得我在某个地方遇到了麻烦,但我不完全确定。

如果我们将$response["data"]和$result-varia移出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;