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

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 success flag) instead of keeping them separate. This ensures your final JSON includes both elements.
  • Success Flag Alignment: Changed true to 1 to match your requirement of success=1.
  • Error Handling: Added a database connection check that returns a success=0 response 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:04:44