dongpaipu8394 2019-02-24 21:44
浏览 79
已采纳

从SQL查询返回的数据创建多维数组

I've a query to fetch datas from a database:

$query = $pdo->prepare('SELECT AVA_Id, AVA_RoomId, AVA_Date, AVA_Status FROM ___Table');
$query->execute();

I'm using this to put all the datas into an array:

while ($fetch = $query->fetch(PDO::FETCH_ASSOC)) {
    $array[] = [
        'AVA_Id' => $fetch['AVA_Id'],
        'AVA_RoomId' => $fetch['AVA_RoomId'],
        'AVA_Date' => $fetch['AVA_Date'],
        'AVA_Status' => $fetch['AVA_Status']
    ];
}

Witch give me the following array:

Array
(
    [0] => Array
        (
            [AVA_Id] => 1
            [AVA_RoomId] => 47
            [AVA_Date] => 2019-02-24
            [AVA_Status] => Open
        )
    [1] => Array
        (
            [AVA_Id] => 2
            [AVA_RoomId] => 48
            [AVA_Date] => 2019-02-26
            [AVA_Status] => Open
        )
)

But how can I return result into a more complex array like this:

Array
(
    [47] => Array
        (
            [2019-02-24] => Array
                (
                    [AVA_Id] => 1
                    [AVA_Status] => Open
                )
        )
    [48] => Array
        (
            [2019-02-26] => Array
                (
                    [AVA_Id] => 2
                    [AVA_Status] => Open
                )

        )
)
  • 写回答

2条回答 默认 最新

  • duanna3634 2019-02-24 21:50
    关注

    You could do that as follows:

    while ($fetch = $query->fetch(PDO::FETCH_ASSOC)) {
        $array[$fetch['AVA_RoomId']][$fetch['AVA_Date']][] = [
            'AVA_Id' => $fetch['AVA_Id'],
            'AVA_Status' => $fetch['AVA_Status']
        ];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗