2

我有一个 API 路由,它将数据库中的记录作为 JSON 输出。我还想输出一个 HTTP 状态码。

我已经尝试在返回之前回显(如下所示)HTTP 状态代码和消息,就像上面一样,它可以按照我想要的方式运行,但是,它不是有效的 JSON,因为我最终得到了两个并排的 JSON 对象。

这是我的代码的简化视图:

private function json_books() {
  $query  = "SELECT title, description FROM books";
  $params= [];

  // creates and prints the HTTP status code message
  $msg = array("status" => "200", "message"=>"OK");
  echo json_encode($msg);

  //returns records from the database as JSON object
  return ($this->recordset->getJSONRecordSet($query, $params));
}

4

2 回答 2

1

如果您可以将记录集作为数组获取,请以如下方式进行:

private function json_books() {
  $query  = "SELECT title, description FROM books";
  $parameters = [];    // you are using the name "params" below!

  //returns records from the database as JSON object along the status message
  return json_encode(array(
    "status" => "200",
    "message" => "OK",
    "result" => $this->recordset->getRecordSet($query, $params)
  ));
}
于 2020-12-02T00:46:51.107 回答
0

您需要创建一个有效的 json 结构。像这样的东西。

private function json_books() {
  $query  = "SELECT title, description FROM books";
  $parameters = [];

  // creates and prints the HTTP status code message
  $msg = array("status" => "200", "message"=>"OK");

  
  // This is prefered so you don't have to convert back and forth from json
  $records_array = $this->recordset->getArrayRecordSet($query, $params);
  
  // If you have to get the values as a json string then you need to convert them
  $records = $this->recordset->getJSONRecordSet($query, $params);
  $records_array = json_decode($records,true);
  
  $msg['data'] = $records_array;
  
  //returns records from the database as JSON string
  return json_encode($msg);
}
于 2020-12-02T00:47:50.463 回答