Symfony2 MySql:获取数组并获取没有列名的JSON数组

时间:2016-03-03 13:51:53

标签: php mysql arrays json symfony

我试图找出如何使用以下格式获取JSON数组

  [
     ["2016-02-26","5190","1253","425","123"],
     ["2016-02-27","5209","1114","521","214"],
     ["2016-02-28","5142","1425","412","156"],
     ["2016-02-29","5523","1365","632","198"],
     ["2016-03-01","5125","1452","523","152"],
     ["2016-03-02","5000","1245","741","286"]
   ]

但目前我正在

  [{"date":"2016-02-26","visitors":"5190","registered":"1253","downloaded":"425","sticky_activity":"123"},
   {"date":"2016-02-27","visitors":"5209","registered":"1114","downloaded":"521","sticky_activity":"214"},
   {"date":"2016-02-28","visitors":"5142","registered":"1425","downloaded":"412","sticky_activity":"156"},{"date":"2016-02-29","visitors":"5523","registered":"1365","downloaded":"632","sticky_activity":"198"},
   {"date":"2016-03-01","visitors":"5125","registered":"1452","downloaded":"523","sticky_activity":"152"},
   {"date":"2016-03-02","visitors":"5000","registered":"1245","downloaded":"741","sticky_activity":"286"}]

这是我的功能,如果它会帮助

  public function dataAction(Request $request){
    $em = $this->getDoctrine()->getEntityManager();
    $connection = $em->getConnection();

    $sqlQuery = "SELECT DATE_FORMAT(date, \"%Y-%m-%d\") as date,visitors, registered, downloaded, sticky_activity
                  FROM engagement";

    $statement = $connection->prepare($sqlQuery);

    $statement->execute();
    $queryResult = $statement->fetchAll();

    return new JsonResponse($queryResult);
}

1 个答案:

答案 0 :(得分:1)

返回:

return new JsonResponse(array_map('array_values', $queryResult));

顺便说一下,您还应该避免直接SQL调用,而不是DQLquery builders。这些都是使用Doctrine时的好习惯。它的目标是尽可能地避免使用SQL。