PacPac
PacPac

Reputation: 261

Create an multidimensional array from the returned datas from a SQL query

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
                )

        )
)

Upvotes: 2

Views: 36

Answers (2)

Rohit Mittal
Rohit Mittal

Reputation: 2104

Use below code:

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

Hope it helps you.

Upvotes: 0

trincot
trincot

Reputation: 349956

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']
    ];
}

Upvotes: 1

Related Questions