PHP:从数据库获取查询结果并将其编码为JSON数组并传递给Android

时间:2016-01-05 02:58:58

标签: php android mysql json

我目前正在使用PHP代码查询一系列字符并找出数据库中的匹配结果。得到结果后,我将其转换为数组。

所以,功能如下。

public function findFriends($name) {
    $connection = $this->db->connect();
    $query = "SELECT name FROM users WHERE lower(users.`name`) LIKE '%$name%'";

    $return_arr = array();
    $fetch = mysqli_query($connection, $query);

    while($row = mysqli_fetch_array($fetch)) {
        $return_arr[] = $row['name'];   
    }

    return $return_arr;
}

上面返回的值,我现在将其编码为JSON数组。

$user = $db->findFriends($name);

if ($user != false) {

    $response["error"] = FALSE;
    $response["user"]["name"] = $user["name"];

    echo json_encode($response);

}

现在,我在Android中获得了JSON数据。

JSONObject jsonObject = new JSONObject(response);
JSONArray arr = jsonObject.getJSONArray("user");

for(int i=0; i<arr.length(); i++) {
    JSONObject jsonData = arr.getJSONObject(i);
    String item = jsonData.getString("name");
}

但这似乎是一个问题。当我在Android应用程序中运行代码并开始查询时,我收到这样的消息。

JSONException caught: Value user of type java.lang.String cannot be converted to JSONArray.

3 个答案:

答案 0 :(得分:0)

在循环访问db结果的php中,试试这个。

    while($row = mysqli_fetch_array($fetch)) {
    $return_arr[] = array("name"=>$row['name']);   
}

    $new_array[] = array("user"=>$return_arr);
    return $new_array;

然后返回数组的json_encode;

答案 1 :(得分:0)

你搞砸了json结构:

$user = $db->findFriends($name);
// here you'll get ($user = ["name1", "name2", "name3"])

if ($user != false) {

    $response["error"] = FALSE;
    $response["user"]["name"] = $user["name"];

    // and here 'll be ({"error": false, "user": {"name": ["name1", "name2", "name3"]}})
    echo json_encode($response);

}

所以,当你打电话

JSONObject jsonObject = new JSONObject(response);

你会得到:

jsonObject = {"error": false, "user": {"name": ["name1", "name2", "name3"]}}

其中jsonObject["user"]是键值对象,而不是数组。

如果您打算以后不仅要转移name,请执行此操作

public function findFriends($name) {
    $connection = $this->db->connect();
    // safely can extend to something like `SELECT id, name FROM ...`, it won't break json consistency/structure
    $query = "SELECT name FROM users WHERE lower(users.`name`) LIKE '%$name%'";

    $return_arr = array();
    $fetch = mysqli_query($connection, $query);

    while($row = mysqli_fetch_array($fetch)) {
        $return_arr[] = $row; // not "$row['name']"
    }

    return $return_arr;
}

$users = $db->findFriends($name);

if ($user != false) {

    $response["error"] = FALSE;
    $response["user"] = $users; // not "$response["user"]["name"] = $user["name"]"

    echo json_encode($response);

}

注意:......因为它很奇怪:你问PHP服务器端“有没有名字的朋友'Alec'?”并且它回答你“当然,愚蠢,这里是:{”错误“:false,”用户“:[{”name“:”Alec Vasovski“}}}”。您是否打算在未来接收数据时做些什么?比如,给应用程序用户带有smth的那个朋友的链接。比如handleFriendUserClick(int userId),您还需要在json中传输userId吗?呃,没关系,我要离题了......

答案 2 :(得分:0)

尝试使用json_encode转储您创建的JSON。我想你会学到很多,并想出你的数组是如何转换成JSON对象的。