0

我使用 Slim Framework 以 JSON 格式返回结果。

$app->get('/forecast_range/{latitude}/{longitude}/{timeStart}/{timeEnd}', function (Request $request, Response $response) {

    $latitude  = $request->getAttribute('latitude');
    $longitude = $request->getAttribute('longitude');
    $timeStart = $request->getAttribute('timeStart');
    $timeEnd   = $request->getAttribute('timeEnd');

    $timeStart = new DateTime($timeStart);  
    $timeEnd   = new DateTime($timeEnd);

    $coordinates[] = array('latitude' => $latitude, 'longitude' => $longitude);

    $forecast = new forecast_range_url($coordinates, 1, $timeStart, $timeEnd);
    $result = $forecast->runForecast(true);    

    return $response->withJson($result);

});

$result变量已经是一个 JSON,一个多维的。我怎样才能将 $result 变量返回给客户端而无需再次对其进行编码?

我尝试使用此代码将$resultkeysJSON 附加到响应中。我觉得我很接近但还没有。我收到语法错误。

 $lenght = count($result);        

    for ($i=0; $i<$lenght; $i++){
        $response->write($result[$i]);    
    }    

    $newResponse = $response->withHeader(
        'Content-type',
        'application/json; charset=utf-8'
    );

    return $newResponse;
4

2 回答 2

0
return $response->write('{"json":"message"}')
          ->withHeader('Content-Type', 'application/json');

只需将其直接写入流,不要忘记设置正确的内容类型 :)

于 2016-07-22T15:42:05.327 回答
0

我想我怎么能返回一个已经格式化的 JSON。我需要将“,”和“[]”附加到response否则数据不会采用正确的 JSON 语法。

这就是我带来的:

$result = $forecast->runForecast(true);        
$lenght = count($result);              

    for ($i=0; $i<$lenght; $i++){         
        if ($i == 0){
            $response->write('['.$result[$i].',');                     
        }
        elseif($i == $lenght - 1)
        {
            $response->write($result[$i].']');
        }
        else
        {
            $response->write($result[$i].',');                        
        }
    }          

$newResponse = $response->withHeader('Content-type', 'application/json; charset=utf-8');
return $newResponse;
于 2016-07-26T14:06:16.800 回答