如何将json数组添加到php

时间:2015-07-04 18:25:28

标签: php json

我正在尝试将JSON数组添加到JSON对象。我的代码就像这样

{
  "status": "True",
  "users": {
    "id": "16",
    "name": "user",
    "email": "user@example.com",
    "friends": [
      {
        "id": "11",
        "name": "frnd1",
        "email": "frnd@example.com"
      },
      {
        "id": "12",
        "name": "frnd2",
        "email": "frnd@example.com"
      }
    ]
  }
}

我在执行以下代码时遇到JSONException,

 // check for user
    $user = $db->getUserByEmailAndPassword($username, $password);
    if ($user != false) {
        // user found
            $response["status"] = "True";
            $userID = $user["id"];
            $response["users"]["id"] = $user["id"];
            $response["users"]["name"] = $user["name"];
            $response["users"]["email"] = $user["email"];
            $result = mysqli_query($con1,"SELECT * 
                                         FROM friends 
                                         where userID = '$userID'");
            $response["users"]["friend"]=array();
            while($row = mysqli_fetch_array($result))
            {
               array_push($response["users"]["friend"], $row);
            }
     }
     echo json_encode($response);

我在这个文件中建立了$ con1连接。 谁能指出我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

试试这个

// check for user
$user = $db->getUserByEmailAndPassword($username, $password);
if ($user != false) {
    // user found
    $response["status"] = "True";
    $userID = $user["id"];
    $response["users"]["id"] = $user["id"];
    $response["users"]["name"] = $user["name"];
    $response["users"]["email"] = $user["email"];
    $result = mysqli_query($con1,"SELECT * 
                                  FROM friends 
                                  WHERE userID = '$userID'");
    while($row = mysqli_fetch_array($result)) {
        $response["users"]["friends"][] = $row;
    }
 }
 echo json_encode($response);

答案 1 :(得分:0)

为什么,之后还有额外的email

最后的元素不需要逗号。

<强>替换

{
    "status": "True",
    "users": {
        "id": "16",
        "name": "user",
        "email": "user@example.com",
        "friends": [
            {
                "id": "11",
                "name": "frnd1",
                "email": "frnd@example.com",//comma not needed here
            },
            {
                "id": "12",
                "name": "frnd2",
                "email": "frnd@example.com",//here too
            }
        ]
    }
}

<强>与

{
    "status": "True",
    "users": {
        "id": "16",
        "name": "user",
        "email": "user@example.com",
        "friends": [
            {
                "id": "11",
                "name": "frnd1",
                "email": "frnd@example.com"
            },
            {
                "id": "12",
                "name": "frnd2",
                "email": "frnd@example.com"
            }
        ]
    }
}