为了在网格中输出它,我必须具有如下所示的JSON语法:
{
"data": [
{
"SupplierID": 1,
"CompanyName": "Exotic Liquids",
"ContactName": "Charlotte Cooper",
"ContactTitle": "Purchasing Manager",
"Address": "49 Gilbert St.",
"City": "London",
"Region": null,
"PostalCode": "EC1 4SD",
"Country": "UK",
"Phone": "(171) 555-2222",
"Fax": null,
"HomePage": null
},
{
"SupplierID": 2,
"CompanyName": "New Orleans Cajun Delights",
"ContactName": "Shelley Burke",
"ContactTitle": "Order Administrator",
"Address": "P.O. Box 78934",
"City": "New Orleans",
"Region": "LA",
"PostalCode": "70117",
"Country": "USA",
"Phone": "(100) 555-4822",
"Fax": null,
"HomePage": "#CAJUN.HTM#"
},....more data...
]
}
这是我正在使用的代码:
mysql_connect('localhost','root','')or die(mysql_error());
mysql_select_db('testdb')or die(mysql_error());
$result = mysql_query("select * from city");
$data[]=array();
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
$jsondata=json_encode($rows);
echo $data[$jsondata];
}
但我有一些错误。
Notice: Undefined index:
我该如何解决这个问题?谢谢
答案 0 :(得分:1)
您需要先将编码数据添加到数组
$data =array();
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
$jsondata=json_encode($rows);
$data[] = $jsondata;
}
现在你可以回应整个事情(可能有一种更简单的方法)
echo explode( $data, ',' );
另外,我认为你可以一次编码整个数组。
答案 1 :(得分:1)
您过早地编码数据。通常你应该构造整个多维数组,然后才进行编码
mysql_select_db('testdb') or die(mysql_error());
$result = mysql_query("select * from city");
$data = array('data' => array());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data['data'][] = $row;
}
echo json_encode($data);