从2个查询返回同一正文中的2个回复

时间:2017-09-06 23:49:30

标签: php mysql arrays json

我有这个功能正常的查询,我希望在不使用JOIN回复的情况下调用更多数据

这是我的查询

$id = $request->getAttribute('id');

$sql = "SELECT *
            FROM users
            WHERE section = :id"; 

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

        $stmt->bindParam(":id", $id);

        $stmt->execute();

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

        $db = null;

        if(empty($users)) {
            $response->getBody()->write
            ('
            {
                "error":
                {
                    "message":"Empty"
                }
            }');
        } else {
            $response->getBody()->write(json_encode($users));
        }
    } catch(PDOException $e) {}
};

我尝试了什么

$id = $request->getAttribute('id');

$tsql = "SELECT *
         FROM teachers
         WHERE section = :id"; 

$sql = "SELECT *
        FROM users
        WHERE section = :id"; 

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

        $stmt->bindParam(":id", $id);
        $tstmt->bindParam(":id", $id);

        $stmt->execute();
        $tstmt->execute();

        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $teachers = $tstmt->fetchAll(PDO::FETCH_OBJ);

        $db = null;

        if(empty($users) AND empty($teachers)) {
            $response->getBody()->write
            ('
            {
                "error":
                {
                    "message":"Empty"
                }
            }');
        } else {
            $response->getBody()->write(json_encode($users));
            $response->getBody()->write(json_encode($teachers));
        }
    } catch(PDOException $e) {}
};

我得到的结果

我得到了我需要的数据,但它像未格式化的json响应, 通常我会得到一个干净的回应"绿色"但是现在我把它全部放在了#34;黑色"

{"userid":"3","firstname":"joe","lastname":"d"}[{"id":"1","name":"jlo"}]

我期待的结果

  1. 清除json格式化的响应
  2. 教师使用标识符"老师"和另一个带有标识符"用户"的数组;包含其中所有数组的数组

1 个答案:

答案 0 :(得分:0)

您需要合并数据并输出一次......

你可以尝试:

$response->getBody()->write(json_encode(['users' => $users, 'teachers' => $teachers]));

这将允许您访问您的数据,如:result.users / result.teachers,并输出如下:

{ "users" : [user1...], "teachers" : [teacher1...] }