目标是从 .php 以 JSON 格式返回数组。该数组包含另一个数据数组(49 行 DB,每行 4 列),该数组取自 mySQL DB:
.php 如下:
$json = array( //this is AJAX response
"status" => null,
"username" => null,
"population" => null,
"food" => null,
"water" => null,
"map" => null //this to be an array of tiles
);
$sql = "SELECT * FROM players_map_test WHERE player_id = :value";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$json["map"]["tile_health"] = $row["tile_health"];
$json["map"]["tile_id"] = $row["tile_id"];
$json["map"]["tile_level"] = $row["tile_level"];
$json["map"]["tile_type"] = $row["tile_type"];
}
echo json_encode($json);
在我的 AJAX 响应处理程序中,我希望将该子数组作为 response.map 访问,并以通常的方式处理元素:response.map[0]。
当我 console.log(response) 时,我看到 map 存在,但它不是一个数组,它包含“1”作为所有键的值:
map:Object
tile_health:"1"
tile_id:"1"
tile_level:"1"
tile_type:"1"
我做错了什么?
最佳答案
更新你的foreach循环,如下所示--
foreach ($result as $row) {
$json["map"][] = $row;
}
同时更改以下代码
#$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
注意: fetch() 函数仅返回 1 行。并且 fetchAll() 函数返回多行。
关于php - 作为 JSON 响应的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39947352/