2014-05-13 210 views
1

我在我的php頁面中使用JSON。我從我的MySQL數據庫格式化JSON數據。但不知何故json數據格式不正確。如何獲得json數組

{"imei":"44fd02f38e4a5c0c","dolgota":"49.406","shirota":"53.5412","date":"2014\/05\/13 13:24:16"}{"imei":"a2422857b2cccf4c","dolgota":"49.4385","shirota":"53.5142","date":"2014\/05\/13 11:22:09"} 

但我想

[{"imei":"44fd02f38e4a5c0c","dolgota":"49.406","shirota":"53.5412","date":"2014\/05\/13 13:24:16"},{"imei":"a2422857b2cccf4c","dolgota":"49.4385","shirota":"53.5142","date":"2014\/05\/13 11:22:09"}] 

這是我的代碼

$dbh = mysql_connect($host, $user, $pswd) or die("Не могу соединиться с MySQL."); 
mysql_select_db($database) or die("Не могу подключиться к базе."); 
$query = "SELECT * FROM `kordinates`"; 
$res = mysql_query($query); 
while($row = mysql_fetch_array($res)) 
{ 
    $json_data = array('imei'=>$row['imei'],'dolgota'=>$row['dolgota'],'shirota'=>$row['shirota'],'date'=>$row['date']); 
    echo json_encode($json_data); 
} 

我該怎麼辦呢?

回答

2

首先採取的所有數據在陣列比使用json_encode你的循環完成後,

while($row = mysql_fetch_array($res)) 
{ 
    $json_data[] = array('imei'=>$row['imei'],'dolgota'=>$row['dolgota'],'shirota'=>$row['shirota'],'date'=>$row['date']);  
} 
echo json_encode($json_data); 

華林:Please, don't use mysql_* functions in new code。他們不再維護and are officially deprecated。請參閱red box?請改爲了解prepared statements,並使用PDOMySQLi - this article將幫助您決定哪個。如果您選擇PDO,here is a good tutorial

+0

哎呀我是緩慢的XD –

0

然後只要把你的數組中的數組:

$json_data = 
array(array('imei'=>$row['imei'],'dolgota'=>$row['dolgota'],'shirota'=>$row['shirota'],'date'=>$row['date']));