我试图用逗号分隔的数组创建JSON

时间:2017-07-31 07:39:08

标签: php json

我需要像这样输出。

{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.6192875","lng":"77.0261699"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6236227","lng":"77.0317984"},{"name":"","lat":"28.6244627","lng":"77.0322383"},{"name":"","lat":"28.6245415","lng":"77.0331425"},{"name":"","lat":"28.6245418","lng":"77.0331053"},{"name":"","lat":"28.6246156","lng":"77.0322415"},{"name":"","lat":"28.6242647","lng":"77.0316073"}

PHP脚本

$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql);
while ($row=mysql_fetch_assoc($result)) {
  $json_array = json_encode($row);
  print_r($json_array);
}

当前输出

{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.6192875","lng":"77.0261699"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6236227","lng":"77.0317984"}{"name":"","lat":"28.6244627","lng":"77.0322383"}{"name":"","lat":"28.6245415","lng":"77.0331425"}{"name":"","lat":"28.6245418","lng":"77.0331053"}{"name":"","lat":"28.6246156","lng":"77.0322415"}{"name":"","lat":"28.6242647","lng":"77.0316073"}

由于

2 个答案:

答案 0 :(得分:3)

在调用JSON编码之前,您需要创建所需的整个对象:

$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql); //You need to switch to mysqli , mysql is no longer a valid choice
$json_array = [];
while ($row=mysql_fetch_assoc($result)) {
    $json_array[] = $row;
}
$jsonString = json_encode($json_array);
print_r($jsonString);

答案 1 :(得分:0)

有多种方法可以解决您的问题"。

但首先,不要使用mysql_ * functions => deprecated in PHP 5.5
改为使用mysqli_ *函数。

如果你只有几百行,你可能会建立一个包含所有项目的数组,比如Paul Crovella和apokryfos说。 但如果有数千行,您应该尽可能快地将它们写出来并且不要将它们保存到RAM中。因为PHP在RAM中的空间有限。

也许你可以在没有循环的情况下尝试:

.flatMap(observable -> observable.onBackpressureDrop())