如何通过循环查询结果来生成数组数组

时间:2017-08-18 19:39:41

标签: php mysql arrays json

我有关于游戏的调查,我有一个用于游戏数据的表格,另一个用于人们的答案。

我想以Json格式输出一个数组,以获得3个最喜欢的游戏名称中的每一个的答案以及它们在数组数组中的年份。

预期输出

[
    {
    "id": "1",
    "username": "userX",
    "g1": {"name": "game1", "year": "1991"},
    "g2": {"name": "game2", "year": "1992"},
    "g3": {"name": "game3", "year": "1993"},
    }
]

我尝试过的内容

$sql = "SELECT * FROM tbAnswers AS answer INNER JOIN tbgames AS game ON answer.g1 = game.id";

try {
    $db = new db();
    $db = $db->connect();
    $stmt = $db->prepare($sql);

    $stmt->execute();

    $answer = $stmt->fetchAll(PDO::FETCH_OBJ);

    $db = null;

    if(empty($answer)) {
        $response->getBody()->write
        ('
        {
            "error":
            {
                "status":"400",
                "message":"Invalid Request"
            }
        }');
    } else {
        $response->getBody()->write(json_encode($answer));
    }
} catch(PDOException $e) {
    $response->getBody()->write
    ('
    {
        "error":
        {
            "message":'. $e->getMessage() .'
        }
    }');
}

当前输出

[
    {
    "id": "1",
    "username": "userX",
    "name": "game1",
    "year": "1991"
    }
]

我认为我应该在其他地方做一个foreach来完成每个游戏并根据答案中的id回应它的结果,但我不确定如何应用它

  1. 在哪里放置foreach
  2. 如何根据每个游戏ID选择并获得结果
  3. 如何以json格式进行操作
  4. 我确定我不是这样做的,这就是我试图回应其他方面的数据

    echo"[";
    echo"\n{";
    echo"\n";
    echo '"id:"'.' "'.$answer[0]->id.'",';
    echo"\n";
    echo"}\n";
    echo"]";
    

    这是我的表结构

    tbGames

        id   ,  name    ,  year
         1   , 'game1'  , '1991'
         2   , 'game2'  , '1992'
         3   , 'game3'  , '1993'
         4   , 'game4'  , '1994'
    

    tbAnswers

       id   ,    name    ,    g1    ,   g2    ,   g3
        1   ,    userX   ,    1     ,   2     ,    3  
        2   ,    userY   ,    3     ,   1     ,    4
        3   ,    userZ   ,    1     ,   1     ,    2
        4   ,    userW   ,    2     ,   3     ,    4
    

1 个答案:

答案 0 :(得分:0)

使用此查询:

$sql = "SELECT answer.id a_id, answer.name a_name, game1.id g1_id, game1.name g1_name, game1.year g1_year, game2.id g2_id, game2.name g2_name, game2.year g2_year, game3.id g3_id, game3.name g3_name, game3.year g3_year FROM tbAnswers AS answer INNER JOIN tbgames AS game1 ON answer.g1 = game1.id INNER JOIN tbgames AS game2 ON answer.g2 = game2.id INNER JOIN tbgames AS game3 ON answer.g3 = game3.id";

您应该将您的其他语句内容更改为:

} else {
    foreach($answer as $value) {
        $array_resp[]=[
            'id' => $value->a_id,
            'username' => $value->a_name,
            'g1' => ['name'=>$value->g1_name, 'year'=>$value->g1_year],
            'g2' => ['name'=>$value->g2_name, 'year'=>$value->g2_year],
            'g3' => ['name'=>$value->g3_name, 'year'=>$value->g3_year],
            ];
    }
    $response->getBody()->write(json_encode($array_resp));
}