簡體   English   中英

我在php中的json響應中需要幫助

[英]I need help in json response in php

這是我的代碼:

<?php
while ($row = mysqli_fetch_assoc($searching_user))
{
    $salon_name = ucfirst($row['service_name']);
    $salon_id = ucfirst($row['id']);
    $salon_address = ucwords($row['address']);
    $salon_area = ucwords($row['area']);
    $salon_city = ucwords($row['city']);
    $salon_specialty = ucwords($row['specialty']);
    $img = $row['image_url'];
    $response["error"] = FALSE;
    $response["service_name"] = $salon_name;
    echo json_encode($response);
}
?>

之后,我得到這種格式的響應

{“錯誤”:false,“ service_name”:“邁克沙龍”} {“錯誤”:false,“ service_name”:“米歇爾沙龍”} {“錯誤”:錯誤,“服務名”:“米歇爾沙龍”} {“錯誤”:false,“ service_name”:“ Mike Salon”} {“錯誤”:false,“ service_name”:“ Etta Salon”}

我只是想要這樣的回應

[{“ error”:false,“ service_name”:“ Mike salon”},{“ error”:false,“ service_name”:“ Michel salon”},{“ error”:false,“ service_name”:“ Michel salon” },{“ error”:false,“ service_name”:“邁克沙龍”},{“ error”:false,“ service_name”:“ Etta Salon”}]

請幫助我為json獲取正確的響應表。 謝謝

不要將單個結果json_encode()放入,而是將它們放入數組中,最后放入json_encode():

<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
  $salon_name = ucfirst($row['service_name']); 
  $salon_id = ucfirst($row['id']);
  $salon_address = ucwords($row['address']);
  $salon_area = ucwords($row['area']);
  $salon_city = ucwords($row['city']);
  $salon_specialty = ucwords($row['specialty']);
  $img = $row['image_url'];

  $response[] = [
    'error' => FALSE,
    'service_name' => $salon_name,
    // you may want to add more attributes here...
  ];
}
echo json_encode($response);

我個人建議縮短此時間:

<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
  $response[] = [
    'error'           => FALSE,
    'service_name'    => ucfirst($row['service_name']),
    'salon_id'        => $row['id'],
    'salon_address'   => ucwords($row['address']),
    'salon_area'      => ucwords($row['area']),
    'salon_city'      => ucwords($row['city']),
    'salon_specialty' => ucwords($row['specialty']),
    'img'             => $row['image_url'],
  ];
}
echo json_encode($response);

您正在嘗試對單個結果進行編碼,嘗試創建一個數組將所有結果並在循環外進行編碼。

while ($row=mysqli_fetch_assoc($searching_user)) {
    $salon_name = ucfirst($row['service_name']);
     $salon_id = ucfirst($row['id']);
     $salon_address = ucwords($row['address']);
     $salon_area = ucwords($row['area']);
     $salon_city = ucwords($row['city']);
     $salon_specialty = ucwords($row['specialty']);
     $img = $row['image_url'];
     $response["error"] = FALSE;
     $response["service_name"]=$salon_name;
     // Added this line
     $responses[] = $response;
}
//Encode all results
 echo json_encode($responses );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM