我对php和JSON非常陌生,我有下面的代码:我也想从头开始学习所有这些东西,请给我推荐一些书。提前谢谢。
if (mysqli_num_rows($result) > 0) {
// looping through all results
// products node
$response = array();
while ($row = mysqli_fetch_array($result)) {
// temp user array
$treklocations = array();
$treklocations["id"] = $row["id"];
$treklocations["name"] = $row["name"];
$treklocations["description"] = $row["description"];
$treklocations["path"] = $row["path"];
$treklocations["difficulty"] = $row["difficulty"];
$treklocations["test"] = $row["test"];
// push single product into final response array
array_push($response, $treklocations);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
这将生成以下格式的输出:
{"0":
{"id":"1"
,"name":"Rajmachi"
,"description":"Rajmachi Trek"
,"path":"http:\/\/192.168.1.105\/Images\/TrekLocations\/1467881880_rajmachi-fort-top-area.jpg"
,"difficulty":"Hard"
,"test":"Test"
}
,"success":1}
但是我想要这种格式的输出:
[{
"title": "Dawn of the Planet of the Apes",
"image": "api.androidhive.info/json/movies/1.jpg",
"rating": 8.3,
"releaseYear": 2014,
"genre": ["Action", "Drama", "Sci-Fi"]
},
{
"title": "District 9",
"image": "api.androidhive.info/json/movies/2.jpg",
"rating": 8,
"releaseYear": 2009,
"genre": ["Action", "Sci-Fi", "Thriller"]
}]
发布于 2019-04-15 04:21:12
您的问题是,正如您所说的{"0":"object_deducted"}
,$response
是索引和关联值的混合,它们将在您的json中创建
为了解决这个问题,我将$response
更改为一个关联数组,这样它就可以有success
和data
,后者是您提取的数据的索引数组
if (mysqli_num_rows($result) > 0) {
// create an associative array
$response = [
'data' => [],
'success' => 1
];
while ($row = mysqli_fetch_array($result)) {
// add an associative array into our indexed array (data)
// $response['data'][] means add new value to the array ( key would be index number )
$response['data'][] = [
'id' => $row["id"],
'name' => $row["name"],
'description' => $row["description"],
'path' => $row["path"],
'difficulty' => $row["difficulty"],
'test' => $row["test"]
];
}
// echoing JSON response
echo json_encode($response);
}
https://stackoverflow.com/questions/55679507
复制相似问题