dongzhong7299 2018-11-13 04:57
浏览 240
已采纳

使用php将sqlite数据转换为json

I'm trying to convert sqlite query into json. I have the following table with two columns name and age. When I print the query the format doesn't seem to be correct. why am I getting an extra key value pair?

<?php
$db = new SQLite3('info.db');

$results = $db->query('SELECT * FROM info');
while ($row = $results->fetchArray()) {

    $jsonArray[] = $row;
}

echo json_encode($jsonArray)
?>

output

[{"0":"billy","name":"billy","1":"20","age":"20"}]

desired output

    [{"name":"billy","age":"20"}]
  • 写回答

2条回答 默认 最新

  • douhe4608 2018-11-13 05:13
    关注

    Change query to get only those column which are required:

    $results = $db->query('SELECT name,age FROM info'); 
    // if you want all column then only use *
    

    And then use SQLITE3_ASSOC

    while($row = $results->fetchArray(SQLITE3_ASSOC)){ 
    

    Reference:- SQLite3Result::fetchArray

    Parameters

    mode

    Controls how the next row will be returned to the caller. This value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH.

    SQLITE3_ASSOC: returns an array indexed by column name as returned in the corresponding result set

    SQLITE3_NUM: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

    SQLITE3_BOTH: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

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

报告相同问题?

悬赏问题

  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发