从 PHP 生成 JSON 响应


Generate JSON Response from PHP

我是PHP的新手,我正在制作移动应用程序并为它构建Web服务。从移动 IM 发送 2 个参数作为 POST 并希望将数据作为 JSON 数据检索。

下面是我的PHP代码。

header('Content-type: application/json');
include 'connection.php';
$response = array();
$location = $_POST['location'];
$country = $_POST['country'];

        $query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
        $result = mysqli_query($conn, $query);

        if (mysqli_num_rows($result) != 0)
      {
          $response["Result"] = 1;
          $response["message"] = "Here Data";
      }else{
          $response["Result"] = 0;
          $response["message"] = "No Data";
      }

echo json_encode($response);
$conn->close();

当我测试当前响应时如下所示。

{"Result":1,"message":"Here Data"}

但是我还想检索结果数据以及上述响应消息。

{
    "Result": 1,
    "Message": "Here Data",
    "Feeds": [
        {
            "userid": "2",
            "name": "Demo",
            "address": "Demo"
        },
         {
            "userid": "2",
            "name": "Demo",
            "address": "Demo"
        }
    ]
}

您还希望迭代 SQL 查询的结果。

header('Content-type: application/json');
include 'connection.php';
$response = array();
$location = $_POST['location'];
$country = $_POST['country'];

    $query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
    $result = mysqli_query($conn, $query);

    if (mysqli_num_rows($result) != 0)
  {
      $response["Result"] = 1;
      $response["message"] = "Here Data";
      while($feed = mysqli_fetch_array($result, MYSQLI_ASSOC){
          $response['Feeds'][] = $feed;
      }
  }else{
      $response["Result"] = 0;
      $response["message"] = "No Data";
  }

echo json_encode($response);
$conn->close();

这里是解决方案。您还应该在 $response 数组中推送查询结果。使用了mysqli_fetch_assoc功能。 header('Content-Type: application/json')在发送任何实际输出之前必须调用,我建议你把你的脚本放在末尾,以避免可能的错误

include 'connection.php';
$response = array();
$location = $_POST['location'];
$country = $_POST['country'];

$query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) != 0) {
    $response["feeds"] = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $response["feeds"][] = $row;
    }
    $response["Result"] = 1;
    $response["message"] = "Here Data";
} else {
    $response["Result"] = 0;
    $response["message"] = "No Data";
}
$conn->close();

header('Content-type: application/json');
echo json_encode($response);