【问题标题】:PHP MySQL and json_encode without quotes around value?PHP MySQL和json_encode值没有引号?
【发布时间】:2015-06-25 19:00:30
【问题描述】:

我有一个正在运行查询的 MySql 表

<?php
// Make a MySQL Connection
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("GPS") or die(mysql_error());

// Get all the data from the "example" table
$myquery = "SELECT * FROM GPSCoords";
$query = mysql_query($myquery) or die(mysql_error());  
$data = array();

for ($x =0; $x < mysql_num_rows($query); $x++){
  $data[] = mysql_fetch_assoc($query);
}

echo json_encode($data);
?>

返回的json是这样的:

[
  {
    "Row": "01SS",
    "Number": "1E",
    "Latitude": "33.39064308000000",
    "Longitude": "-121.918467900",
    "LatLong": "[33.39064308000000,-121.918467900]"
  }
]

如何将 LatLong 值设为不带引号的值?

[
  {
    "Row": "01SS",
    "Number": "1E",
    "Latitude": "33.39064308000000",
    "Longitude": "-121.918467900",
    "LatLong": [
      33.39064308000000,
      -121.918467900
    ]
  }
]

【问题讨论】:

标签: php mysql json


【解决方案1】:

这样强制:

while ($row = mysql_fetch_assoc($result)) {
    $row["Latitude"] = floatval($row["Latitude"]);
    $row["Longitude"] = floatval($row["Longitude"]);
    $data[] = $row;
}

至于

"LatLong": "[33.39064308000000,-121.918467900]"

这很奇怪,看起来您将此 JSON 数组作为字符串存储在数据库中。

你可以这样做:

$latLong = json_decode($row["LatLong"], true);
$row["LatLong"] = array(floatval($latLong[0]), floatval($latLong[1]));

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多