格式化JsonArray php

时间:2017-06-23 14:30:44

标签: php android arrays json

我想以这种方式格式化,但我无法  目前它看起来像这样:

    {"success":true,"user":"tom","gender":"male","age":"2"}
{"success":true,"user":"anna","gender":"female","age":"3"}

但它看起来应该是这样的

  {
      "result":[ 
                 {"success":true,"user":"tom","gender":"male"},
                 {"success":true,"user":"anna","gender":"female"}
               ]
    }

这是我的代码

if ($result->num_rows > 0)
  {
    while($row = $result->fetch_assoc())
     {
       $user= $row["user"];
       $gender= $row["gender"];

       $response["user"] = $user;
       $response["gender"] = $gender;
       $response["success"] = true;

       echo json_encode($response); 

     }
   }

1 个答案:

答案 0 :(得分:1)

if ($result->num_rows > 0)
  {
    while($row = $result->fetch_assoc())
     {
       $user= $row["user"];
       $gender= $row["gender"];

       $response['result'][] = [
           'user' => $user,
           'gender' => $gender,
           'success' => true
       ];

     }
     echo json_encode($response);
   }

您在每个循环上对其进行格式化,这将输出完全独立的JSON集。