2012-02-24 78 views
0

为了在网格中输出它,我必须有像如下所示的JSON语法:语法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:

我怎样才能解决这个问题?,感谢

回答

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); 
+0

是啊!多数民众赞成它,我忘记了一个多阵列多么愚蠢的我。谢谢.. – tomexsans 2012-02-24 14:41:07

1

你需要的编码数据添加到阵列第一

$data =array(); 
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){ 
$jsondata=json_encode($rows); 
$data[] = $jsondata; 
} 

现在你可以重复整个事情(有可能是一个更简单的方法)

echo explode($data, ','); 

另外,我想你可能能够一次编码整个数组。