0

I have the following table in my mysql database with events with start and end TIME datatype:

start_time  end_time    day 
08:00:00    16:00:00    1
08:00:00    16:00:00    1
08:00:00    16:00:00    4
08:00:00    16:00:00    5

I want to create a multidimensional array with this where each day have it's start_time and end_time in an array, like this;

array:3 [
    1 => array:2 [
        0 => array:2 [
            0 => "08:00"
            1 => "16:00"
        ]
        1 => array:2 [
            0 => "08:00"
            1 => "16:00"
        ]
    ]
    4 => array:1 [
        0 => array:2 [
            0 => "08:00"
            1 => "16:00"
        ]
    ]
    5 => array:1 [
        0 => array:2 [
            0 => "08:00"
            1 => "16:00"
        ]
    ]
]

I have a variable with all events in which i could foreach to go through.

Is this doable or do I need to use pivot tables to keep these two values seperated?

Thanks!

2 Answers 2

1

Loop through your fetched rows and use the day as the key and dynamically add an element [] and assign the times as an array:

foreach($rows as $row) {
    $result[$row['day']][] = array($row['start_time'],
                                   $row['end_time']);
}

Or do it when fetching from the DB:

while($row = /* fetch_function() */) {
    $result[$row['day']][] = array($row['start_time'],
                                   $row['end_time']);
}
Sign up to request clarification or add additional context in comments.

Comments

1
<?php
 $records = array(
    array(
        'start_time' => '00:11:22',
        'end_time'   => '11:22:33',
        'day' => 1
    ),
    array(
        'start_time' => '20:11:22',
        'end_time'   => '21:22:33',
        'day' => 2
    ),
    array(
        'start_time' => '10:11:22',
        'end_time'   => '11:22:33',
        'day' => 1
    )

); // Your actual data would replace this of course

 $sorted = array();
 foreach($records as $record){
     // Group by day
     $sorted[$record['day']][] = $record;
 }


 // Group again
 $results = array();
 foreach($sorted as $day => $records){
     foreach($records as $record){
        $results[$day][] = 
        array($record['start_time'],$record['end_time']);   
     }

 }

 var_dump($results);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.