我正在使用PHP从MSSQL数据库中检索数据,我想将其格式化为JSON,因为这是我开发图表的唯一方法(借助 am chart < /强>)。
这是我的代码:
<?php
header('Content-Type: applicaton/json');
$serverName = "server\sqlexpress";
$connectionInfo = array( "Database"=>"myDB", "UID"=>"myUID", "PWD"=>"myPWD");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn==true ) {
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));}
//QUERY
$sql = "SELECT FIRSTNAME, LASTNAME, JOBTYPE from directory ORDER BY JOBTYPE";
$stmt = sqlsrv_query( $conn, $sql);//, $params);
if( $stmt) {
// echo "Statement executed.<br>\n";
}
else
{
echo "error in statement execution.\n";
die (print_r (sqlsrv_errors(), true));
}
//PRINT ROWS
$data = array();
while ($row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH))
{
$data[] = $row;
//echo $row['LASTNAME']. ' | ' .$row['FIRSTNAME']. ' | ' .$row['JOBTYPE']. "<br>" ;
}
echo json_encode($data);
?>
我认为我的输出数据格式如下:
[{"LASTNAME": "MEINE",
"FIRSTNAME": "KLAUS",
"JOBTYPE": "LEADVOICE"
},
{"LASTNAME": "SCHENKER",
"FIRSTNAME": "RUDOLF",
"JOBTYPE": "RYTHMGUITAR"
}]
但它输出如下:
[{"0":"KLAUS",
"FIRSTNAME":"KLAUS",
"1":"MEINE",
"LASTNAME":"MEINE",
"2":" LEADVOICE",
"JOBTYPE":" LEADVOICE"
},
{"0":"RUDOLF",
"FIRSTNAME":"RUDOLF",
"1":"SCHENKER",
"LASTNAME":"SCHENKER",
"2":" RYTHMGUITAR",
"JOBTYPE":" RYTHMGUITAR"
}]
发生了什么以及为什么会发生?
提前致谢!!
答案 0 :(得分:0)
只需替换下面的行
$data[] = $row;
使用
$row_data['LASTNAME'] = $row['LASTNAME'];
$row_data['FIRSTNAME] = $row['FIRSTNAME'];
$row_data['JOBTYPE'] = $row['JOBTYPE'];
array_push($data,$row_data);