【问题标题】:Rest API single item - json format problemRest API单项-json格式问题
【发布时间】:2019-03-09 19:35:40
【问题描述】:

我的 API 将单个项目作为对象返回:

"data":{"id":1,"name":"Test"}

但我需要数组中的此项,如下所示:

"data":[{"id":1,"name":"Test"}]

data.json:

[
  {"id": 1, "name":"Test"},
  {"id": 2, "name": "Test2"}
]

api.php:

function getData2($id) {
 $jsonString = '';
 $jsonData = file_get_contents($jsonString);
 $data2 = json_decode($jsonData, true);
 return $data2[$id - 1];
}
if (!empty($_GET['id'])) {
 $a = getData2($_GET['id']);
}
response($a);
function response($data) {
 header("HTTP/1.1 ".$status);
 $response['data'] = $data;
 $jsonResponse = json_encode($response);
 echo $jsonResponse;
}

提前致谢。

【问题讨论】:

    标签: php json rest


    【解决方案1】:

    只需将数据放入这样的数组中:

    function response($data) {
    header("HTTP/1.1 ".'200');
    
    $response['data'] = [$data];
    
    $jsonResponse = json_encode($response);
    echo $jsonResponse;
    }
    

    注意这一行中的 $data $response['data'] = [$data];

    【讨论】:

      猜你喜欢
      • 2014-11-15
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多