多维数组作为JSON响应

时间:2016-10-09 18:57:40

标签: php mysql arrays

目标是以JSON格式从.php返回数组。该数组包含另一个数据数组(49个数据库行,每个数据库有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(响应)时,我看到那里有地图,但它不是一个数组,它包含" 1"作为所有键的值:

map:Object
    tile_health:"1"
    tile_id:"1"
    tile_level:"1"
    tile_type:"1"

我做错了什么?

3 个答案:

答案 0 :(得分:1)

更新 foreach 循环,如下所示 -

foreach ($result as $row) {
  $json["map"][] = $row;
}

同时更改以下代码

#$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

注意: fetch()函数只返回1行。 fetchAll()函数返回多行。

答案 1 :(得分:0)

语法是下一个:

foreach ($result as $row) {
    $json["map"][] = [
        "tile_health" => $row["tile_health"],
        "tile_id" => $row["tile_id"],
        "tile_level" => $row["tile_level"],
        "tile_type" => $row["tile_type"]
    ];
}

你覆盖了价值观。

答案 2 :(得分:0)

您可以像这样简化数据库部分:

// request only needed columns
$sql = "SELECT tile_health, tile_id, tile_level, tile_type 
        FROM players_map_test WHERE player_id = :value";

$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

// output was already in the type of array
$json["map"] = $result;

// encode and display
echo json_encode($json);