gpt4 book ai didi

php - 如何正确获取 JSONArray 项?

转载 作者:行者123 更新时间:2023-11-29 15:37:04 25 4
gpt4 key购买 nike

我有一个 php 文件,我从数据库中检索数据,然后将其转换为数组,然后对其进行编码,因此我正在开发的 Android 应用程序获取 JSONArray 解析它,并获取数据。

这是 php 文件:

<?php

$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();
$dbh = $db->connect(); // here you get the connection

$query = "SELECT *FROM lost_pets";

$result = $dbh->prepare($query);
$result->execute();

if ($result->fetchAll() > 0) {
foreach($dbh->query($query) as $row){
$pet["id"] = $row['id'];
$pet["name"] = $row['name'];
$pet["breed"] = $row['breed'];

$response["pet"] = array($pet);
echo json_encode($response);
}
}
?>

这是结果:

{"pet":[{"id":"1","name":"Prueba","breed":"Yorkshire Terrier"}]}{"pet":[{"id":"2","name":"Prueba2","breed":"German Shepherd"}]}{"pet":[{"id":"3","name":"Prueba3","breed":"Beagle"}]}

问题是,当我在 Android 中检索 JSONObject 并执行 getJSONArray() 时,我没有给我 3 个数组,而是得到了上述结果。

我确实对 PHP 不是很了解,但是根据 php 文档,我看不出我做错了什么。我非常接近完成应用程序,这是我现在唯一无法解决的大问题,这真的让我很沮丧。谢谢!

编辑:JSON解析器

else if(method.equals("GET")){
// request method is GET

if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}

try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
is = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + '\n');
}
is.close();
json = sb.toString();
System.out.println(json.toString() + "This is the json");
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}catch (NullPointerException ex){
System.out.println("No internet");
}

return jObj;

}

conn.disconnect();
return jObj;
}

最佳答案

您需要 array_push 将 $pet 插入数组并打印该数组。使用,

<?php
$arr=array();
foreach($dbh->query($query) as $row){
$pet["id"] = $row['id'];
$pet["name"] = $row['name'];
$pet["breed"] = $row['breed'];
$response["pet"] = array_push($arr,$pet);
}

print_r($arr);

?>

关于php - 如何正确获取 JSONArray 项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47596252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com