从SQL Server检索数据并将其转换为json格式? [英] Retrieving data from SQL Server and turning it into a json format?

查看:121
本文介绍了从SQL Server检索数据并将其转换为json格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP 5.6.0,并已连接到本地SQL Server.我能够检索数据,但是它是数组格式.我想将其转换为json格式.

I am using PHP 5.6.0 and connected to my local SQL Server. I was able to retrieve the data, but it is in an array format. I would like to convert it into a json format.

我得到的:

(     
    [date] => 2013-02-05 16:02:02.000000
    [timezone_type] => 3
    [timezone] => America/New_York
)

我想要的东西:

(
    "date" : "2013-02-05 16:02:02.000000",
    "timezone_type" : "3",
    "timezone" : "America/New_York"
)

这是我的代码:

$sql = "SELECT * FROM table";
$stmt = sqlsrv_query($conn, $sql);

$result = array(); 

do {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
    $result[] = print_r($row); 
    }
} while (sqlsrv_next_result($stmt));


echo json_encode($result);


sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

我的理解是json_encode应该可以转换我的数据,但这种方式似乎行不通.

My understanding is that json_encode should convert my data but it doesn't seem to work that way.

谢谢!

推荐答案

我猜您的代码中有两个错误.第一个是

I guess there were two mistakes in your code. First one is

$result[] = print_r($row); 

您正在执行一个函数,并同时将值推入数组.您应该在此处将值推送到数组中.喜欢

You are executing a function and pushing values in array at same time. You should push value in array here. Like

$result[] = $row;

第二个是,在对JSON varibale进行编码后不进行打印.因此您的代码应为

And Second one is, not printing the JSON varibale after encoding it. So your code would be

$sql = "SELECT * FROM table";
$stmt = sqlsrv_query($conn, $sql);

$result = array(); 

do {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
       $result[] = $row; 
    }
} while (sqlsrv_next_result($stmt));


sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first

echo json_encode($result); //You will get the encoded array variable

这篇关于从SQL Server检索数据并将其转换为json格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆