JSON API 的 Slim $app->render 问题

Slim $app->render issues for a JSON API

这是一个相当简单的 Slim $app->render 问题,但我正在使用 SQL 查询 return table 中的总列数 table 通过 $result,里面存储的数据是这样的:[{"total":"12345"}]

我想像这样将其推送到 JSON API:

$app->get('/api/total/', function() use ($app) {
  $query = "select count(*) AS total FROM sometable";
  $data = $app->db->query($query);
  $result = $data->fetchAll(PDO::FETCH_OBJ);
  $app->render(
    200, json_encode(array(
      'total' => $result['total']
    ))
  );
});

如何让 Slim 的 $app->render 产生 {total:12345}

执行 'total' => $result['total'] 会引发错误,例如:

NOTICE: Undefined index: total

是因为fetchAll returns数组的结果。您可以改用 fetch()。检查获取是否没有失败也很好。但是,在这种特殊情况下,如果存在某个表,则不应该存在。您还使用 fetch_obj 并尝试将其作为错误的数组访问。使用 FETCH_ASSOC 或使用具有适当对象访问权限的 FETCH_OBJ

$app->get('/api/total/', function() use ($app) {
  $query = "select count(*) AS total FROM sometable";
  $data = $app->db->query($query);
  $result = $data->fetch(PDO::FETCH_OBJ);
  if($result !== false) {
    $app->render(
     200, json_encode(array(
      'total' => $result->total
      ))
   );
  } else {
     $app->render(
     404, json_encode(array(
      'error' => 'Not Found'
      ))
   );
  }
 });

另外记得设置内容类型就好了

$app->response->headers->set('Content-Type', 'application/json');

如果您需要了解抓取的工作原理,请检查:http://php.net/manual/en/pdostatement.fetch.php