K. Nathan
K. Nathan

Reputation: 17

How to prevent duplicated values in a multidimentional array php

I have this code:

<?php

$schedules = array();
$schedules[0]['start_hour'] = "08:00:00";
$schedules[1]['start_hour'] = "08:15:00";
$schedules[2]['start_hour'] = "08:30:00";
$schedules = json_encode($schedules);
$schedules = json_decode($schedules, FALSE);

for ($i = strtotime("08:00:00"); $i <= strtotime("09:00:00"); $i = $i+15*60):
    foreach($schedules as $sch):
        if($i == strtotime($sch->start_hour)):
            echo date("H:i", $i)." SCHEDULED! <br>";
        else:
echo date("H:i", $i)." NOT SCHEDULED :( <br />";
        endif;
    endforeach;
endfor;

?>

I have this first for, who goes from 08:00:00 to 09:00:00 each 15 minutes, and I have this second foreach, who check inside this array, which hours I have scheduled. i have this if who check which hours in the first for is in the schedules array, and print it, and if is not in the array, print as NOT SCHEDULED. The problem is, when I have 2 or more schedules in the array, the output duplicate the values. In this example, the output is:

08:00 SCHEDULED!
08:00 NOT SCHEDULED :(
08:00 NOT SCHEDULED :(
08:15 NOT SCHEDULED :(
08:15 SCHEDULED!
08:15 NOT SCHEDULED :(
08:30 NOT SCHEDULED :(
08:30 NOT SCHEDULED :(
08:30 SCHEDULED!
08:45 NOT SCHEDULED :(
08:45 NOT SCHEDULED :(
08:45 NOT SCHEDULED :(
09:00 NOT SCHEDULED :(
09:00 NOT SCHEDULED :(
09:00 NOT SCHEDULED :(

and I want something like:

08:00 SCHEDULED!
08:15 SCHEDULED!
08:30 SCHEDULED!
08:45 NOT SCHEDULED :(
09:00 NOT SCHEDULED :(

What can I do?

Upvotes: 0

Views: 31

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94672

Start by simplifying the process, make a simpe array of the booked times so you can use in_array() inside a single loop

$schedules = array();
$schedules[0]['start_hour'] = "08:00:00";
$schedules[1]['start_hour'] = "08:15:00";
$schedules[2]['start_hour'] = "08:30:00";

#Make simple array of booked times
$booked = [];
foreach ( $schedules as $sch ):
    $booked[] = strtotime($sch['start_hour']);
endforeach;

for ($i = strtotime("08:00:00"); $i <= strtotime("09:00:00"); $i = $i+15*60):
    if( in_array($i, $booked)):
        echo date("H:i", $i)." SCHEDULED! \n";
    else:
        echo date("H:i", $i)." NOT SCHEDULED :( \n";
    endif;
endfor;

RESULT

08:00 SCHEDULED! 
08:15 SCHEDULED! 
08:30 SCHEDULED! 
08:45 NOT SCHEDULED :( 
09:00 NOT SCHEDULED :( 

Upvotes: 1

Related Questions