dongyong6045 2016-04-01 18:38
浏览 61
已采纳

使用php编码json

So here the thing:

I am developing a backend (php) that connects with Microsoft SQL Server with android application to be the user interface.

However, I am facing a problem when it comes to encoding json with php.

It is more than fair to say that I am a beginner in php.

This is my code:

$result = sqlsrv_query( $conn, 'select * from table1');
 $row = sqlsrv_fetch_array($result);
 $array = array();
while($row =sqlsrv_fetch_array($result))
{
    $array[]=$row;
}
echo json_encode(array("data"=>array_values($array)));

So the table actually has nothing so far: just two attributes: name and age

The problem here is that the return is being as follows:

{"data":[{"0":"Miriana","name":"Miriana","1":null,"age":null},{"0":"Luke","name":"Luke","1":null,"age":null},{"0":"Sara","name":"Sara","1":null,"age":null},{"0":"Fuss","name":"Fuss","1":20,"age":20}]}

There is always a number preceding the values with a value then the real key and a value.

For example:

"0":"Miriana"
 "1":null

Thanks so much for anyone who would check this out.

**I checked those links: Decode json With PHP not working Parsing JSON with PHP Encoding JSON with PHP issues with array **

  • 写回答

2条回答 默认 最新

  • dongzanghong4379 2016-04-01 18:43
    关注

    The default fetch type of sqlsrv_fetch_array is SQLSRV_FETCH_BOTH, which fetches the rows as associative and numeric array, so you get both types. If you only want an associative array, set the second argument of sqlsrv_fetch_array to SQLSRV_FETCH_ASSOC.

    $result = sqlsrv_query( $conn, 'select * from table1');
    $array = array();
    while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
    {
        $array[]=$row;
    }
    echo json_encode(array("data"=>array_values($array)));
    

    Removed the first fetch, because you will not get the first row if you do that.

    Reference: http://php.net/manual/en/function.sqlsrv-fetch-array.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址