如何在PHP中将JSOn对象转换为JSonArray

时间:2017-07-26 16:28:37

标签: php json

我有以下JSon对象结果,我想将其转换为JSonARray:

{"error":false,"user":{"paid_amount":"500","parking_duration":"59min","parking_name":"asass"}} {"error":false,"user":{"paid_amount":"100","parking_duration":"22min","parking_name":"SDSDASDAS"}}

我需要的输出如下,我需要将所有结果放在一个数组中  [{"error":false,"user":{...}}, {"error":false,"user":{...}}]

[{"error":false,"user":{"paid_amount":"500","parking_duration":"59min","parking_name":"asass"}}, {"error":false,"user":{"paid_amount":"100","parking_duration":"22min","parking_name":"SDSDASDAS"}}]

Php代码:

    .......
 // json response array
 $response = array("error" => FALSE);

 if (isset($_POST['plate_no'])) {

    // receiving the post params
      $plate_no = $_POST['plate_no']; 
   // get the user 
   $usersArr = $db->getDriverHistory($plate_no);

    if ($usersArr != false) {
     foreach($usersArr as $key=>$user){

    // use is found
   $response[$key]["error"] = FALSE;
  $response[$key]["user"]["paid_amount"] = $user["paid_amount"];
  $response[$key]["user"]["parking_duration"] = $user["parking_duration"];
  $response[$key]["user"]["parking_name"] = $user["parking_name"];
   $response = $response[$key];

  echo json_encode($response), "<br>";

      } 
    }
   .....

1 个答案:

答案 0 :(得分:0)

只需替换下面给出的最后一行:

$data[] = $response[$key];
echo json_encode($data);