PDO:将属性分组而不是重复行

时间:2017-02-25 21:21:47

标签: php arrays pdo

早上好,

我有一个请求,它会向我返回一些预订信息,每个预订都可以链接到多个房间。

每次有多个房间进行预订时,是否可以有一个房间阵列而不是重复该行。

我想要的是什么:

[
    idReservation1 => [
        "client_name" => "kévin titi",
        "checkin" => "2017-08-08",
        "d_checkout" => "2017-08-10",
        "email" => "titi@gmail.com",
        room_id => [1,2,3,9]//here I want an array
    ],
    idReservation2 => [
        "client_name" => "firstname lastname",
        "checkin" => "2017-08-18",
        "d_checkout" => "2017-08-20",
        "email" => "toto@gmail.com",
        "room_id" => [1,12,13,9]//here I want an array
    ]
]

如果idReservation不是关键没关系,重要的是这里有一个数组用于room_id 我已经查看了所有PDO获取模式,但它们似乎与我的问题不匹配。

我的要求:

 $prep = $this->pdo->prepare("
            SELECT re.id as resId, re.client_name, re.d_checkin, re.d_checkout, re.mail, ro_re.room_id as room
            FROM Reservation re
            JOIN Room_Reservation ro_re ON ro_re.reservation_id = re.id
            WHERE re.confirmed = false
        ");

由于

1 个答案:

答案 0 :(得分:1)

假设您正在使用 MySql :使用GROUP_CONCAT功能的解决方案(为每个预订分组房间 ID) :

$stmt = $this->pdo->prepare("
            SELECT 
                re.id as resId, re.client_name, re.d_checkin, re.d_checkout, re.mail, 
                GROUP_CONCAT(ro_re.room_id SEPARATOR ',') AS room_ids
            FROM 
                Reservation re
                INNER JOIN Room_Reservation ro_re ON ro_re.reservation_id = re.id
            WHERE re.confirmed = false
            GROUP BY re.id
");

$stmt->execute();

// `room_ids` column will contain a string like "1,2,3,9"
$result = [];
foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
    $row['room_ids'] = explode(',', $row['room_ids']);  // converting string with room ids into array
    $result[] = $row;
}