如何格式化动态数组进行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_EXCEPTIONso any query failures (not just connection issues) are caught in your try/catch block, making debugging easier. - Data Casting: Converting
dining_latanddining_longto 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
restaurantskey—this is exactly the structure you specified. - Proper Headers: Setting
Content-Type: application/jsontells 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
相关产品推荐
相关产品推荐

