Reputation: 321
OK I'm querying the database and populating an array with the results but I don't want to get duplicates.
$start = date('c', $row['start_time']);
while (strtotime($end) < $row['end_time']){
$title = 'Teacher Available';
$color = '#a3a3a3';
$end = date('c', strtotime($start) + hoursToSeconds($row_Branch['session']));
$allday = ($row['allDay'] == "1") ? true : false;
if (in_array($start, $input_arrays) == false){
$input_arrays[]= array(title => $title, start => $start, end => $end, color => $color, allDay => $allday);
}
$start = date('c', strtotime($end));
}
In my way of thinking this should not add a new entry to the array if there is already an entry with the same $start but for some reason it adds it anyway.
Can anyone see where I am going wrong?
Upvotes: 1
Views: 61
Reputation: 3300
$start
is set to the string returned by date('c',...
). $input_arrays
is an array where each element is also an array.
So, when you test in_array($start, $input_arrays, true)
, it will test if your string is equal to each of the arrays within the $input_arrays
array. A string is always NOT equal to an array, especially since you specified true
which means the types must match.
There's a number of ways to fix this, depending on what you want, including ...
...
if ( !array_key_exists($start, $input_arrays) ){
$input_arrays[$start]= array(title => $title, start => $start, end => $end, color => $color, allDay => $allday);
}
...
EDIT: To get $input_arrays
with keys 0,1,2,... as required by your calendar module, add this statement just after your while
loop:
$input_arrays = array_values($input_arrays);
Upvotes: 2
Reputation: 3300
$start
is set to the string returned by date('c',...
). $input_arrays
is an array where each element is also an array. A non-empty string is always NOT equal to a non-empty array so your in_array
always returns false. Try this ...
$start = date('c', $row['start_time']);
$startTimesAlreadyAdded = [];
while (strtotime($end) < $row['end_time']){
$title = 'Teacher Available';
$color = '#a3a3a3';
$end = date('c', strtotime($start) + hoursToSeconds($row_Branch['session']));
$allday = ($row['allDay'] == "1") ? true : false;
if ( !in_array($start, $startTimesAlreadyAdded) ) {
$input_arrays[] = array(title => $title, start => $start, end => $end, color => $color, allDay => $allday);
$startTimesAlreadyAdded[] = $start;
}
$start = date('c', strtotime($end));
}
This will leave you with $input_arrays
with keys 0,1,2,... as required by your calendar module.
Upvotes: 1