You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何格式化动态数组进行JSON编码?谷歌地图坐标JSON构建求助

Solution: Formatting Dynamic Array for Google Maps JSON

Got it, let's adjust your PHP code to generate the exact JSON structure you need for Google Maps coordinates. Here's the complete, working version with explanations:

<?php
try {
    $conn = new PDO('mysql:host=localhost;dbname=dining', 'root', 'mypasswordhere');
    // Enable exception handling for query errors (not just connection issues)
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $qry = "SELECT dining_lat, dining_long FROM dining_listings";
    $getData = $conn->query($qry);
    
    $restaurants = [];
    // Loop through each database row to build your lat/lng objects
    foreach ($getData->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $restaurants[] = [
            'lat' => (float)$row['dining_lat'], // Cast to float to ensure numeric JSON values
            'lng' => (float)$row['dining_long']
        ];
    }

    // Build the final JSON structure and encode it
    $jsonOutput = json_encode(['restaurants' => $restaurants]);
    
    // Set the correct HTTP header for JSON responses (critical for API clients)
    header('Content-Type: application/json');
    echo $jsonOutput;

} catch (PDOException $e) {
    // Handle errors gracefully with a JSON error response
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(['error' => $e->getMessage()]);
    exit;
}
?>

Key Details:

  • PDO Error Mode: Added PDO::ERRMODE_EXCEPTION so any query failures (not just connection issues) are caught in your try/catch block, making debugging easier.
  • Data Casting: Converting dining_lat and dining_long to floats ensures they appear as numeric values in the JSON (not quoted strings), which matches your desired format.
  • Structure Matching: We wrap the array of lat/lng objects inside a parent array with the restaurants key—this is exactly the structure you specified.
  • Proper Headers: Setting Content-Type: application/json tells browsers or API clients that the response is JSON, which is essential for Google Maps to parse it correctly.

Example Output:

If your database has the coordinates you listed, this code will output:

{"restaurants":[{"lat":-84.9834,"lng":85.8374},{"lat":-84.8378,"lng":85.8374},{"lat":-84.7384,"lng":85.3784}]}

内容的提问来源于stack exchange,提问作者Hayden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:51:02