PHP SQLSRV return JSON

PHP SQLSRV return JSON

我正在使用 SQL 服务器数据库,因此我正在调整语法。

我正在尝试 return 一些 JSON,但我似乎无法正确设置格式。

在我的 PHP 脚本中,我有以下代码:

 <?php
   $select = "SELECT
                CONCAT('\"',COALESCE('',''),'\"') AS EDIT
                ,CONCAT('\"',COALESCE([FOR_PARTNER],''),'\"') AS PARTNER_CODE
                ,CONCAT('\"',COALESCE([FOR_NAME],''),'\"') AS PARTNER_NAME
                ,CONCAT('\"',COALESCE([SHP_PARTNER],''),'\"') AS SHIPPER_PCODE
                ,CONCAT('\"',COALESCE([SHP_NAME],''),'\"') AS SHIPPER_NAME
                ,CONCAT('\"',COALESCE([MODDATE],''),'\"') AS MODDATE
                ,CONCAT('\"',COALESCE([MODUSER],''),'\"') AS MODUSER
                ,CONCAT('\"',COALESCE([ID],''),'\"') AS ID
             FROM
                [main].[dbo].[exceptions]";

 $query = sqlsrv_query($dbc, $select);
 $resnum = sqlsrv_num_rows($query);

 // here is where the error lies

 echo "{\"data\":[";
 $i = 1;    
 while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC))
 {
   echo "[";
     echo implode(', ', $row);
   echo "]";
   if($i < $resnum){
     echo ",";
   }
   $i++;
 }
 echo "]}";

 sqlsrv_free_stmt($query);
 ?>

使用上面的代码,returned 的 JSON 看起来像这样:

 {"data":[["", "0000111111", "JBR", "00000999999", "AMERICA INC", "Jan 1 1900 12:00AM", "", "55"]["", "0000777777", "7ALEXANDER LOG", "000222222", "NORRIS INC", "Jan 1 1900 12:00AM", "", "56"]]}

如果您注意到,内部数组之间没有逗号分隔。它应该像这样 returned:

 {"data":[["", "0000111111", "JBR", "00000999999", "AMERICA INC", "Jan 1 1900 12:00AM", "", "55"],["", "0000777777", "7ALEXANDER LOG", "000222222", "NORRIS INC", "Jan 1 1900 12:00AM", "", "56"]]} 

我使用了与 MySQL 相同的语法,但当然是 MySQL。我在上面使用 SQLSRV。我不确定 IMPLODE 是否被理解了。

所以简而言之,我需要用逗号分隔内部数组。

有人看到我的错误吗?

这是您的代码示例:

<?php

$select = "SELECT
            PARTNER_CODE, PARTNER_NAME, SHIPPER_PCODE, SHIPPER_NAME, MODDATE, MODUSER, ID
         FROM
            [main].[dbo].[exceptions]";

$query = sqlsrv_query($dbc, $select);
$res = [];

while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_NUMERIC) ) {
// you need SQLSRV_FETCH_NUMERIC for your result, but i prefere to use SQLSRV_FETCH_ASSOC
    $res[] = $row;
}

sqlsrv_free_stmt($query);
echo json_encode( [ 'data' => $res ] );