怎么得到json数组

时间:2014-05-13 09:29:57

标签: php json

我在php页面中使用JSON。我正在从我的mysql数据库格式化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 个答案:

答案 0 :(得分: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);

Waring: 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

答案 1 :(得分:0)

然后把你的数组放在一个数组中:

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