我正在尝试将数据输入到具有CRUD操作的网格中,该网格称为Jquery JTable,但是从MYSQL表到JSON的Json转换似乎存在某种错误,因为要在表上显示数据它需要看起来像这样:
{
"Result":"OK",
"Records":[
{"PersonId":1,"Name":"Benjamin Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":2,"Name":"Douglas Adams","Age":42,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":3,"Name":"Isaac Asimov","Age":26,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":4,"Name":"Thomas More","Age":65,"RecordDate":"\/Date(1320259705710)\/"}
]
}
但每当我在php中实现json_encode
函数时,它就会给我这个:
{
"Result":"OK",
"Records":[
{"0":"1","PersonId":"1","1":"Benjamin Button","Name":"Benjamin Button","2":"17","Age":"17","3":"2011-12-27 00:00:00","RecordDate":"2011-12-27 00:00:00"},
{"0":"2","PersonId":"2","1":"Douglas Adams","Name":"Douglas Adams","2":"42","Age":"42","3":"2011-12-26 00:00:00","RecordDate":"2011-12-26 00:00:00"},
{"0":"3","PersonId":"3","1":"Isaac Asimov","Name":"Isaac Asimov","2":"26","Age":"26","3":"2011-12-28 00:00:00","RecordDate":"2011-12-28 00:00:00"},
{"0":"4","PersonId":"4","1":"Thomas More","Name":"Thomas More","2":"61","Age":"61","3":"2011-12-27 00:00:00","RecordDate":"2011-12-27 00:00:00"},
{"0":"5","PersonId":"5","1":"Ihsan Oktay Anar","Name":"Ihsan Oktay Anar","2":"44","Age":"44","3":"2012-01-03 20:55:02","RecordDate":"2012-01-03 20:55:02"}
]
}
这是我的PHP代码:
<?php
//Get records from database
$result = mysqli_query($conn, "SELECT * FROM people;");
//Add all records to an array
$rows = array();
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
?>
该表称为人员,它有四个字段:personId
,Name
,Age
和RecordDate
。
非常感谢任何想法。
答案 0 :(得分:1)
您可能想尝试mysqli_fetch_assoc()
功能。
因为根据关于mysqli_fetch_array()
的PHP文档:
将结果行提取为关联行,数字数组或两者
这是您现在使用代码体验的内容,因为默认提取模式为MYSQLI_BOTH
:
... "1":"Benjamin Button","Name":"Benjamin Button" ...
你也可以使用mysqli_fetch_array()
但是你必须调整获取模式:
mysqli_fetch_array($result, MYSQLI_ASSOC);