PHP生成JSON异常:需带success=1供Android Spinner使用却仅返回数组
Hey there! Let's get this sorted out for you. The core issue here is that you’re creating two separate arrays but not combining them into a single structure that includes both the success=1 flag and your workorder names array. Let’s fix that step by step.
Fixing the JSON Response for Android Spinner
First, here’s the adjusted code that will generate the exact JSON structure you need:
<?php require_once('connection.php'); // Query to fetch workorder names $workName = "SELECT workorder_name FROM workorder_category"; $con = mysqli_connect($server_name, $user_name, $password, $db); // Add a connection check to handle errors gracefully if (!$con) { die(json_encode(['success' => 0, 'message' => 'Database connection failed: ' . mysqli_connect_error()])); } $r = mysqli_query($con, $workName); // Initialize main response array with success flag set to 1 $response = array('success' => 1); $workorderList = array(); // Loop through query results to build the workorder names array while($row = mysqli_fetch_assoc($r)) { $workorderList[] = $row['workorder_name']; } // Attach the workorder list to the main response array $response['workorders'] = $workorderList; // Output the combined JSON structure echo json_encode($response); // Clean up the database connection mysqli_close($con); ?>
Key Changes & Explanations:
- Combined Structure: We merged your workorder names array into the main response array (which holds the
successflag) instead of keeping them separate. This ensures your final JSON includes both elements. - Success Flag Alignment: Changed
trueto1to match your requirement ofsuccess=1. - Error Handling: Added a database connection check that returns a
success=0response if the connection fails—this makes debugging on the Android side way easier. - Cleanup: Added
mysqli_close($con)to properly close the database connection after use.
Example Output JSON:
When you run this code, your output will look like this (perfect for populating your Android Spinner):
{ "success": 1, "workorders": [ "Maintenance Request", "Installation Task", "Repair Job" ] }
On the Android side, you can parse this JSON, verify success is 1, then extract the workorders array to feed into your Spinner adapter.
内容的提问来源于stack exchange,提问作者Chandu
相关产品推荐
相关产品推荐

