nucky
nucky

Reputation: 348

How can I display MySQL-data in an array as in example?

I want to use a solution shown on StackOverflow PHP Determine when multiple(n) datetime ranges overlap each other! To work with it I query the results from MySQL. As in the solution a user can have multiple date entries.

So far I have an array, but it's not grouped by users (named invitees) who have added their dates.

    while ($row = mysqli_fetch_assoc($result)) {

        $arr[$row['invitee']];

        $temp = array($row['start_time'], $row['end_time']);

        $arr[] = $temp;
    }

With the following output result:

Array
(
    [0] => Array
        (
            [0] => 2019-10-16 00:00:00
            [1] => 2019-10-31 23:00:00
        )

    [1] => Array
        (
            [0] => 2019-10-17 12:12:00
            [1] => 2019-10-18 20:40:00
        )

    [2] => Array
        (
            [0] => 2019-10-12 10:00:00
            [1] => 2019-10-24 20:00:00
        )
...

What I expect or want to achieve is an array as shown in the post mentioned above:

$availability = [
    [
        ["2016-04-30 12:00", "2016-05-01 03:00"]
    ],
    [
        ["2016-04-30 03:00", "2016-05-01 03:00"]
    ],
    [
        ["2016-04-30 03:00", "2016-04-30 13:31"],
        ["2016-04-30 15:26", "2016-05-01 03:00"]
    ]
];

to use the solution from the post. But how can I achieve it that my MySQL-data can be displayed like this?

Upvotes: 1

Views: 46

Answers (2)

devpro
devpro

Reputation: 16117

Just need to modify your array inside while as like:

while ($row = mysqli_fetch_assoc($result)) {
    $temp = array(array($row['start_time'], $row['end_time']));
    $arr[$row['invitee']] = $temp; 
}

add one another array here array(array($row['start_time'], $row['end_time']))

Edit:

<?php
$finalArray = array();
while ($row = mysqli_fetch_assoc($result)) {
  $finalArray[$row['invitee']][] = array($row['start_time'], $row['end_time']);
}
?>

Explanation:

With this code you can get multiple invitation against each users.

Upvotes: 1

Coder
Coder

Reputation: 339

See if is working :

    $res = array();
while ($row = mysqli_fetch_assoc($result)) { 
$res[ ]= [$row['start_time'], $row['end_time']];
 }

Upvotes: 0

Related Questions