我有一个从我的数据库中检索一些数据的 PHP 脚本,我想将它编码为 json 以便在我的 Android 应用程序中进行处理。我希望结果是这样的:
{
"part": [
{
"partNo": "value",
"partName": "value",
"shortDesc": "value",
"longDesc": "value",
"image": "value"
},
{
"partNo": "value",
"partName": "value",
"shortDesc": "value",
"longDesc": "value",
"image": "value"
}
],
"success": 1
}
我正在使用以下 PHP 脚本。
// array for JSON response
$response = array();
// execute query based on specified user input
$result = mysql_query($sql) or die(mysql_error());
// check to see if results were found
if (mysql_num_rows($result) > 0) {
//create a part array in $response to hold the part details
$response['part'] = array();
while ($row = mysql_fetch_array($result)) {
//create an array for the part details
$part = array();
$part['partNo'] = $row['partNo'];
$part['partName'] = $row['partName'];
$part['shortDesc'] = $row['shortDesc'];
$part['longDesc'] = $row['longDesc'];
$part['image'] = "data:image/jpeg;base64,".base64_encode($row['image']);
// put the array results for a single part in $response
array_push($response['part'], $part);
}
// add the code for success to $response
$response['code'] = 1;
// and send it in json
echo(json_encode($response));
//print_r($response);
//print_r(json_encode($response));
} else {
//no results found
$response['code'] = 0;
$response['message'] = "No part found!";
echo json_encode($response);
}
?>
我没有收到关于 echo (json_encode($response));
的任何回复或 print_r(json_encode($response));
.但是当我做 print_r($response);
,我正在收到回复!
Array ( [part] => Array ( [0] => Array ( [partNo] => value [partName] => value [shortDesc] => value [longDesc] => value [image] => data:image/jpeg;base64,/9j/4QAYRXhpZgAAS.../9k= ) ) [code] => 1 )
任何人都可以阐明这一点吗?为什么它不适用于 json_encode?p>
最佳答案
仅用于返回 json 格式的 $response
:
header('Content-type: application/json');
echo json_encode($response);
关于php - PHP 中的 json_encode 没有返回任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29502922/