Highcharts :: Codeigniter - php

<?php
for ($i= 1; $i <= 12; $i++) {
if ( $i <= 9) {
$month = '0' . $i;
} else {
$month = $i;
}
$date = date("d");
$year = date("Y");
//$month = date('Y-m-d', strtotime(date('Y').'-'.$i.'-'.date('d')));
$month = date('Y-m-d', strtotime($date."-" . $i ."-". $year));
$where = array('created_time >=' => $month . " 00:00:00", 'created_time <=' => $month . " 23:59:59");
$i_result[$month] = count($this->db->where($where)->get('tbl_opportunities')->result());
} var_dump( $i_result);
?>
I am trying to generate month recap charts. It is giving me the correct result for today's stats, but for the next days the stats refresh and give the new stats. But I would like to have a cumulative of total result for that particular month (monthly basic). Any suggestions?..
Refer to the image - just the blue bar:

manage to solve the problem...Tq
by replace this line
$where = array('created_time >=' => $month . " 00:00:00", 'created_time <=' => $month . " 23:59:59");
to
$where = array('created_time >=' => $year . "-" . '0' . $i . '-' . '01', 'created_time <=' => $year . "-" . '0' . $i . '-' . '31');

Related

How to improve the loading of my PHP script for a calendar with different slots

I have a script that allows me to automatically generate slots on a calendar according to the different opening hours of my users.
Today, I would like to improve the execution of my script to make it much faster than today (it takes a few seconds to make the calendar appear).
You have to know that I have a table OPENING_TIMES which contains 7 rows (1 per day) for each user.
I tried some improvements but without success (with joins for example).
Do you have any ideas?
Thanks in advance !
$Sch_Link_User = $_GET['psy'];
$Data_query = mysqli_query($_Db_Con, 'SELECT ID_UNIQUE, CONSULTATION_TIME, CONSULTATION_TIME_BEFORE, TIMEZONE FROM USERS WHERE PROFILE_URL LIKE "' . $Sch_Link_User . '"');
$Data = mysqli_fetch_assoc($Data_query);
$Sch_Id_User = $Data['ID_UNIQUE'];
$Difference = '0';
switch ($Data['CONSULTATION_TIME']) {
case 1:
$Sch_Time_Consultation = 30;
break;
case 2:
$Sch_Time_Consultation = 45;
break;
case 3:
$Sch_Time_Consultation = 60;
break;
default:
$Sch_Time_Consultation = 60;
}
$Calendar = array();
$weekslots = array_map(function($dow) {return array('dow' => $dow, 'hour' => 00);}, range(0, 6));
$date = time();
$end_date = $date + (6 * 7 * 24 * 60 * 60);
$open_hours_cache = array();
while($date <= $end_date) {
$date_dow = date('w', $date);
foreach($weekslots as $timeslot) {
if($date_dow == $timeslot['dow']) {
$timeofday = $date + (3600 * $timeslot['hour']);
for($nd = 1; $nd <= 7; $nd++) {
if(date('N', $timeofday) == $nd) {
if (!isset($open_hours_cache[$nd])) {
$Data_Openhours_query = mysqli_query($_Db_Con, 'SELECT START_HOUR_M, END_HOUR_M, START_HOUR_A, END_HOUR_A FROM OPENING_TIMES WHERE ID_USER = "' . $Sch_Id_User . '" AND WEEKDAY = "' . $nd . '" AND CLOSED = 0');
$open_hours_cache[$nd] = mysqli_fetch_assoc($Data_Openhours_query);
}
$Data_Openhours = $open_hours_cache[$nd];
if(isset($Data_Openhours['START_HOUR_M']) && $Data_Openhours['END_HOUR_M'] == NULL && $Data_Openhours['START_HOUR_A'] == NULL && isset($Data_Openhours['END_HOUR_A'])) {
$shm = strtotime($Data_Openhours['START_HOUR_M'] . $Difference . ' hour');
$eha = strtotime($Data_Openhours['END_HOUR_A'] . $Difference . ' hour');
$timeslots = array();
$interval = new DateInterval("PT{$Sch_Time_Consultation}M");
$timeRange = new DatePeriod(new DateTime(date('Y-m-d H:i', $shm)), $interval, new DateTime(date('Y-m-d H:i', $eha)));
foreach ($timeRange as $time) {
$timeslots[] = $time->format("H:i");
}
foreach ($timeslots as $slot) {
$datefinal = date('Y-m-d', $timeofday) . ' ' . $slot . ':00';
$timestamp = strtotime($datefinal . $Difference . ' hour');
$Check_Slot = mysqli_query($_Db_Con, 'SELECT ID, ID_USER, STATUS FROM APPOINTMENTS WHERE ID_USER = "' . $Sch_Id_User . '" AND DATE_START = "' . $timestamp . '" AND (STATUS = 1 OR STATUS = 2 OR STATUS = 9 OR STATUS = 10) AND DATE_START > "' . $Time . '"');
$Data_Slot = mysqli_fetch_assoc($Check_Slot);
$status = isset($Data_Slot['STATUS']) && $Data_Slot['STATUS'] == 9 && $Data_Slot['ID_USER'] == $_SESSION['uid'];
$check_slot = mysqli_num_rows($Check_Slot) == 0;
$time_before = ($Time + (60 * 60 * $Data['CONSULTATION_TIME_BEFORE'])) < $timestamp;
if ($status) {
$class = 'blocked';
} elseif ($check_slot && $time_before) {
$class = 'available';
} else {
$class = 'unavailable';
}
$Calendar[] = array(
'id' => date('Y-m-d', $timeofday) . '/' . $slot,
'title' => $slot,
'class' => $class,
'psy' => $Sch_Id_User,
'start' => $timestamp . '000',
);
}
} else if(isset($Data_Openhours['START_HOUR_M']) && isset($Data_Openhours['END_HOUR_M']) && isset($Data_Openhours['START_HOUR_A']) && isset($Data_Openhours['END_HOUR_A'])) {
$shm = strtotime($Data_Openhours['START_HOUR_M'] . $Difference . ' hour');
$ehm = strtotime($Data_Openhours['END_HOUR_M'] . $Difference . ' hour');
$sha = strtotime($Data_Openhours['START_HOUR_A'] . $Difference . ' hour');
$eha = strtotime($Data_Openhours['END_HOUR_A'] . $Difference . ' hour');
$timeslots = array();
$interval = new DateInterval("PT{$Sch_Time_Consultation}M");
$timeRange = new DatePeriod(new DateTime(date('Y-m-d H:i', $shm)), $interval, new DateTime(date('Y-m-d H:i', $ehm)));
foreach ($timeRange as $time) {
$timeslots[] = $time->format("H:i");
}
$timeRange = new DatePeriod(new DateTime(date('Y-m-d H:i', $sha)), $interval, new DateTime(date('Y-m-d H:i', $eha)));
foreach ($timeRange as $time) {
$timeslots[] = $time->format("H:i");
}
foreach ($timeslots as $slot) {
$datefinal = date('Y-m-d', $timeofday) . ' ' . $slot . ':00';
$Check_Slot = mysqli_query($_Db_Con, 'SELECT ID, ID_USER, STATUS FROM APPOINTMENTS WHERE ID_USER = "' . $Sch_Id_User . '" AND DATE_START = "' . strtotime($datefinal) . '" AND (STATUS = 1 OR STATUS = 2 OR STATUS = 9 OR STATUS = 10) AND DATE_START > "' . $Time . '"');
$Data_Slot = mysqli_fetch_assoc($Check_Slot);
// * 24 le temps avant possibilité de prende rendez-vous
$status = isset($Data_Slot['STATUS']) && $Data_Slot['STATUS'] == 9 && $Data_Slot['ID_USER'] == $_SESSION['uid'];
$check_slot = mysqli_num_rows($Check_Slot) == 0;
$time_before = ($Time + (60 * 60 * $Data['CONSULTATION_TIME_BEFORE'])) < strtotime($datefinal . $Difference . ' hour');
if ($status) {
$class = 'blocked';
} elseif ($check_slot && $time_before) {
$class = 'available';
} else {
$class = 'unavailable';
}
$Calendar[] = array(
'id' => date('Y-m-d', $timeofday) . '/' . $slot,
'title' => $slot,
'class' => $class,
'psy' => $Sch_Id_User,
'start' => strtotime($datefinal . $Difference . ' hour') . '000',
);
}
}
}
}
}
}
$date += 86400;
}
$Calendar_Data = array(
'success' => 1,
'result' => $Calendar);
echo json_encode($Calendar_Data);
So I try to have a much faster loading with joins or a cache system to limit the number of requests.
Moreover, wouldn't it be more efficient if I also put everything in one column of my user table, the schedules?

Change language in date()

i have a website with appointments and i use this booking script http://www.planetphp.co.uk/free-php-booking-slots-calendar/.
Unfortunately, i have tried everything to change the language when it shows the month.
class booking_diary {
// Mysqli connection
function __construct($link) {
$this->link = $link;
}
// Settings you can change:
// Time Related Variables
public $booking_start_time = "09:00"; // The time of the first slot in 24 hour H:M format
public $booking_end_time = "21:00"; // The time of the last slot in 24 hour H:M format
public $booking_frequency = 30; // The slot frequency per hour, expressed in minutes.
// Day Related Variables
public $day_format = 3; // Day format of the table header. Possible values (1, 2, 3)
// 1 = Show First digit, eg: "M"
// 2 = Show First 3 letters, eg: "Mon"
// 3 = Full Day, eg: "Monday"
public $day_closed = array("Saturday", "Sunday"); // If you don't want any 'closed' days, remove the day so it becomes: = array();
public $day_closed_text = "CLOSED"; // If you don't want any any 'closed' remove the text so it becomes: = "";
// Cost Related Variables
public $cost_per_slot = 20.50; // The cost per slot
public $cost_currency_tag = "€"; // The currency tag in HTML such as € £ ¥
// DO NOT EDIT BELOW THIS LINE
public $day_order = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
public $day, $month, $year, $selected_date, $back, $back_month, $back_year, $forward, $forward_month, $forward_year, $bookings, $count, $days, $is_slot_booked_today;
/*========================================================================================================================================================*/
function make_calendar($selected_date, $back, $forward, $day, $month, $year,$first_name) {
// $day, $month and $year are the $_GET variables in the URL
$this->day = $day;
$this->month = $month;
$this->year = $year;
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->telephone = $telephone;
$this->email = $email;
$this->page_id = $page_id;
$this->user_id = $user_id;
$this->uid = $uid;
$this->pon = $owner;
$this->rsvnumb = $rsvnumb;
// $back and $forward are Unix Timestamps of the previous / next month, used to give the back arrow the correct month and year
$this->selected_date = $selected_date;
$this->back = $back;
$this->back_month = date("m", $back);
$this->back_year = date("Y", $back); // Minus one month back arrow
$this->forward = $forward;
$this->forward_month = date("m", $forward);
$this->forward_year = date("Y", $forward); // Add one month forward arrow
// Make the booking array
$this->make_booking_array($year, $month);
}
function make_booking_array($year, $month, $j = 0) {
$stmt = $this->link->prepare("SELECT name, date, start FROM bookings WHERE date LIKE CONCAT(?, '-', ?, '%') and page_id=".$_GET['page_id']."");
$this->is_slot_booked_today = 0; // Defaults to 0
$stmt->bind_param('ss', $year, $month);
$stmt->bind_result($name, $date, $start);
$stmt->execute();
$stmt->store_result();
while($stmt->fetch()) {
$this->bookings_per_day[$date][] = $start;
$this->bookings[] = array(
"name" => $name,
"date" => $date,
"start" => $start
);
// Used by the 'booking_form' function later to check whether there are any booked slots on the selected day
if($date == $this->year . '-' . $this->month . '-' . $this->day) {
$this->is_slot_booked_today = 1;
}
}
// Calculate how many slots there are per day
$this->slots_per_day = 0;
for($i = strtotime($this->booking_start_time); $i<= strtotime($this->booking_end_time); $i = $i + $this->booking_frequency * 60) {
$this->slots_per_day ++;
}
$stmt->close();
$this->make_days_array($year, $month);
} // Close function
function make_days_array($year, $month) {
// Calculate the number of days in the selected month
$num_days_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Make $this->days array containing the Day Number and Day Number in the selected month
for ($i = 1; $i <= $num_days_month; $i++) {
// Work out the Day Name ( Monday, Tuesday... ) from the $month and $year variables
$d = (mktime(0, 0, 0, $month, $i, $year));
// Create the array
$this->days[] = array("daynumber" => $i, "dayname" => date("l", $d));
}
/*
Sample output of the $this->days array:
[0] => Array
(
[daynumber] => 1
[dayname] => Monday
)
[1] => Array
(
[daynumber] => 2
[dayname] => Tuesday
)
*/
$this->make_blank_start($year, $month);
$this->make_blank_end($year, $month);
} // Close function
function make_blank_start($year, $month) {
/*
Calendar months start on different days
Therefore there are often blank 'unavailable' days at the beginning of the month which are showed as a grey block
The code below creates the blank days at the beginning of the month
*/
// Get first record of the days array which will be the First Day in the month ( eg Wednesday )
$first_day = $this->days[0]['dayname']; $s = 0;
// Loop through $day_order array ( Monday, Tuesday ... )
foreach($this->day_order as $i => $r) {
// Compare the $first_day to the Day Order
if($first_day == $r && $s == 0) {
$s = 1; // Set flag to 1 stop further processing
} elseif($s == 0) {
$blank = array(
"daynumber" => 'blank',
"dayname" => 'blank'
);
// Prepend elements to the beginning of the $day array
array_unshift($this->days, $blank);
}
} // Close foreach
} // Close function
function make_blank_end($year, $month) {
/*
Calendar months start on different days
Therefore there are often blank 'unavailable' days at the end of the month which are showed as a grey block
The code below creates the blank days at the end of the month
*/
// Add blank elements to end of array if required.
$pad_end = 7 - (count($this->days) % 7);
if ($pad_end < 7) {
$blank = array(
"daynumber" => 'blank',
"dayname" => 'blank'
);
for ($i = 1; $i <= $pad_end; $i++) {
array_push($this->days, $blank);
}
} // Close if
$this->calendar_top();
} // Close function
function calendar_top() {
// This function creates the top of the table containg the date and the forward and back arrows
echo "
<div id='lhs'><div id='outer_calendar'>
<table border='0' cellpadding='0' cellspacing='0' id='calendar'>
<tr id='week'>
<td align='left'><a href='?month=" . date("m", $this->back) . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&telephone=" . $_GET['telephone'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&pon=" . $_GET['pon'] . "&page_id=" . $_GET['page_id'] . "&year=" . date("Y", $this->back) . "'>«</a></td>
<td colspan='5' id='center_date'>" . date("F, Y", $this->selected_date) . "</td>
<td align='right'><a href='?month=" . date("m", $this->forward) . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&telephone=" . $_GET['telephone'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&pon=" . $_GET['pon'] . "&page_id=" . $_GET['page_id'] . "&year=" . date("Y", $this->forward) . "'>»</a></td>
</tr>
<tr>";
/*
Make the table header with the appropriate day of the week using the $day_format variable as user defined above
Definition:
1: Show First digit, eg: "M"
2: Show First 3 letters, eg: "Mon"
3: Full Day, eg: "Monday"
*/
foreach($this->day_order as $r) {
switch($this->day_format) {
case(1):
echo "<th>" . substr($r, 0, 1) . "</th>";
break;
case(2):
echo "<th>" . substr($r, 0, 3) . "</th>";
break;
case(3):
echo "<th>" . $r . "</th>";
break;
} // Close switch
} // Close foreach
echo "</tr>";
$this->make_cells();
} // Close function
function make_cells($table = '') {
echo '<h3>Επέλεξε μία μέρα</h3>';
echo "<tr>";
foreach($this->days as $i => $r) { // Loop through the date array
$j = $i + 1; $tag = 0;
// If the the current day is found in the day_closed array, bookings are not allowed on this day
if(in_array($r['dayname'], $this->day_closed)) {
echo "\r\n<td width='21' valign='top' class='closed'>" . $this->day_closed_text . "</td>";
$tag = 1;
}
// Past days are greyed out
if (mktime(0, 0, 0, $this->month, sprintf("%02s", $r['daynumber']) + 1, $this->year) < strtotime("now") && $tag != 1) {
echo "\r\n<td width='21' valign='top' class='past'>";
// Output day number
if($r['daynumber'] != 'blank') echo $r['daynumber'];
echo "</td>";
$tag = 1;
}
// If the element is set as 'blank', insert blank day
if($r['dayname'] == 'blank' && $tag != 1) {
echo "\r\n<td width='21' valign='top' class='unavailable'></td>";
$tag = 1;
}
// Now check the booking array $this->booking to see whether we have a booking on this day
$current_day = $this->year . '-' . $this->month . '-' . sprintf("%02s", $r['daynumber']);
if(isset($this->bookings_per_day[$current_day]) && $tag == 0) {
$current_day_slots_booked = count($this->bookings_per_day[$current_day]);
if($current_day_slots_booked < $this->slots_per_day) {
echo "\r\n<td width='21' valign='top'>
<a href='reservation.php?month=" . $this->month . "&year=" . $this->year . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&telephone=" . $_GET['telephone'] . "&pon=" . $_GET['pon'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&page_id=" . $_GET['page_id'] . "&day=" . sprintf("%02s", $r['daynumber']) . "' class='part_booked' title='This day is part booked'>" .
$r['daynumber'] . "</a></td>";
$tag = 1;
} else {
echo "\r\n<td width='21' valign='top'>
<a href='reservation.php?month=" . $this->month . "&year=" . $this->year . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&telephone=" . $_GET['telephone'] . "&pon=" . $_GET['pon'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&page_id=" . $_GET['page_id'] . "&day=" . sprintf("%02s", $r['daynumber']) . "' class='fully_booked' title='This day is fully booked'>" .
$r['daynumber'] . "</a></td>";
$tag = 1;
} // Close else
} // Close if
if($tag == 0) {
echo "\r\n<td width='21' valign='top'>
<a href='reservation.php?month=" . $this->month . "&year=" . $this->year . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&telephone=" . $_GET['telephone'] . "&pon=" . $_GET['pon'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&page_id=" . $_GET['page_id'] . "&day=" . sprintf("%02s", $r['daynumber']) . "' class='green' title='Please click to view bookings'>" .
$r['daynumber'] . "</a></td>";
}
// The modulus function below ($j % 7 == 0) adds a <tr> tag to every seventh cell + 1;
if($j % 7 == 0 && $i >1) {
echo "\r\n</tr>\r\n<tr>"; // Use modulus to give us a <tr> after every seven <td> cells
}
}
echo "</tr></table></div><!-- Close outer_calendar DIV -->";
if(isset($_GET['year']))
$this->basket();
echo "</div><!-- Close LHS DIV -->";
// Check booked slots for selected date and only show the booking form if there are available slots
$current_day = $this->year . '-' . $this->month . '-' . $this->day;
$slots_selected_day = 0;
if(isset($this->bookings_per_day[$current_day]))
$slots_selected_day = count($this->bookings_per_day[$current_day]);
if($this->day != 0 && $slots_selected_day < $this->slots_per_day) {
$this->booking_form();
}
} // Close function
Have someone any idea about this script and how can i change the language of the month (greek)?
The date() function can only use English for its outputs. You'd have to use strftime() instead, while setting the locale with setlocale(). This will output in the language of the set locale, in this case - greek.
The two have somewhat different formats, but aren't altogether that different. A brief example is given below.
setlocale(LC_TIME, 'el_GR.UTF-8'); // Set the locale to greek
echo strftime("%A", $d); // Outputs weekname, Monday through Sunday
echo strftime("%m", $this->back) // Outputs month, numerically, e.g. "10"
echo strftime("%B, %Y", $this->selected_date); // Outputs e.g "October, 2016"
// These comments, about the formats, are in English,
// because I don't know the Greek translation
// It will be in Greek should the locale be installed and properly set
Change the date() functions to strftime() instead (with the new parameters, found in the documentation), and you should be good!
If the above doesn't work, it's because that locale (el_GR, for Greek) hasn't been installed on your server.
References
http://php.net/manual/en/function.strftime.php
http://php.net/manual/en/function.setlocale.php
Thank you for your answer. i tried setlocale(LC_TIME, 'el_GR.UTF-8'); but nothing happend. I have tried setlocale(LC_ALL, 'greek'); but the greek words are ???????.When i encode page to windows-1253 i can see the month in greek language but this is not a solution. What can i do?
EDIT:
I found the solution
$date_encoded = strftime('%B %Y', $this->selected_date);
$date_encoded = iconv('Windows-1253', 'UTF-8//IGNORE', $date_encoded);
How we can change the default time to dynamic using mysqli db
// Time Related Variables
public $booking_start_time = "09:00"; // The time of the first slot in 24 hour H:M format
public $booking_end_time = "21:00"; // The time of the last slot in 24 hour H:M format

How-to get the start/end Mondays of the month in php

I need to include also the last Monday of the precedent month, and the first Monday of the next month.
Example
2016-01-25
2016-02-01
2016-02-08
2016-02-15
2016-02-22
2016-02-29
2016-03-07
I have this code so far:
function getAllDaysInAMonth($year, $month, $day = 'Monday', $daysError = 3) {
$dateString = 'first ' . $day . ' of ' . $year . '-' . $month;
if (!strtotime($dateString)) {
throw new \Exception('"' . $dateString . '" is not a valid strtotime');
}
$startDay = new \DateTime($dateString);
if ($startDay->format('j') > $daysError) {
$startDay->modify('- 7 days');
}
$days = array();
while ($startDay->format('Y-m') <= $year . '-' . str_pad($month, 2, 0, STR_PAD_LEFT)) {
$days[] = clone($startDay);
$startDay->modify('+ 7 days');
}
return $days;
}
Ok, resolved!
function getAllDaysInAMonth($year, $month, $day = 'Monday', $daysError = 3) {
$dateString = 'first ' . $day . ' of ' . $year . '-' . $month;
if (!strtotime($dateString)) {
throw new \Exception('"' . $dateString . '" is not a valid strtotime');
}
$startDay = new \DateTime($dateString);
if ($startDay->format('j') > $daysError) {
$startDay->modify('- 7 days');
}
$days = array();
$lastMonday = new DateTime("last Monday of last month");
$nextMonday = new DateTime("first Monday of next month");
$days[] = clone($lastMonday);
while ($startDay->format('Y-m') <= $year . '-' . str_pad($month, 2, 0, STR_PAD_LEFT)) {
$days[] = clone($startDay);
$startDay->modify('+ 7 days');
}
$days[] = clone($nextMonday);
return $days;
}
Try this :
$lastMonday = new DateTime("last Monday of last month");
$nextMonday = new DateTime("first Monday of next month");
echo 'Last Monday : '.$lastMonday->format('Y-m-d').'<br />';
echo 'First Monday : '.$nextMonday->format('Y-m-d');

Date changing in loop

Hi I've created an array that has a Start Date that increases by a month and this happens by how many months there are. So if my StartDate was 10/10/15 and placed 3 into my for loop I would receive 10/10/15 10/11/15 10/12/15 10/01/16. My current problem is that I've added a new while loop to find out if some of the days of the months fall on either a Saturday or Sunday.Which I don't want I would like it to fall on a weekday. So ive created this loop and it works however I have another problem. If 10/11/15 fell on a Sunday my loop will change it to 11/11/15 Monday which is correct but the rest of dates after it will now follow the changed date example be 11/12/15, 11/01/16.
I want it change the date but still the other dates to still increase from the startdate (10/10/15) like 10/10/15, 11/11/15, 10/12/15, 10/01/16. How would I do this? I also understand some of my code may not be the best but I am just a beginner. Any help would be much appreciated.
$date = "2015-10-1"; //startdate
$lol = 2; //length of loan
$start = strtotime($date); //startdate
$currentdate = $start;
echo "<pre>";
$times_table = [];
$titles[] = [
'Version' => 'Version 5 ',
'Date' => 'Feb-16',
'Name' => 'gary',
'RandNum' => '80',
'PaymentType' => 'P',
'dtType' => 'Q',
];
$times_table = [];
for($i = 0; $i <= ($lol + 1) ; $i++){
$times_table[$i]['StartDate']= $date ;
$times_table[$i]['Version']= "v10" ;
$cur_date = date("M-y-D", $currentdate);
$times_table[$i]['DtMy']= "<strong>" . $cur_date . "</strong>" ;
$mthYr = date("M", $currentdate);
$nxtmth = " ";
// Loop that changes the day to a weekday
while($nxtmth != "Y" ) {
if( $cur_date = date("M", $currentdate) !== $mthYr){
$nxtmth = "Y";
$currentdate = strtotime('-1 days', $currentdate);
$cur_date = date("d-M", $currentdate);
$times_table[$i]['DtMy']= "<strong>" . $cur_date . "</strong>" ;
}
if ($cur_date = date("w", $currentdate) == 0 || $cur_date = date("w", $currentdate) == 6){
if ($nxtmth == "Y"){
$currentdate = strtotime('-1 day', $currentdate);
$cur_date = date("d-M", $currentdate);
$times_table[$i]['DtMy']= "<strong>" . $cur_date . "</strong>" ;
}
else{
$currentdate = strtotime('+1 day', $currentdate);
$cur_date = date("d-M", $currentdate);
$times_table[$i]['DtMy']= "<strong>" . $cur_date . "</strong>" ;
}
if(($cur_date = date("M", $currentdate)) !== $mthYr){
$nxtmth = "Y";
$currentdate = strtotime('-1 day', $currentdate);
$cur_date = date("d-M", $currentdate);
$times_table[$i]['DtMy']= "<strong>" . $cur_date . "</strong>" ;
}
}
if($cur_date = date("w", $currentdate) > 0 && $cur_date = date("w", $currentdate) < 6 ){
$cur_date = date("d-M", $currentdate);
$times_table[$i]['DtMy']= "<strong>" . $cur_date . "</strong>" ;
break;
}
}
$currentdate = strtotime('+1 month', $currentdate); //Adds 1 month
}
print_r($times_table);
echo "</ pre>";
You can simply store the value in temp variable before overwriting
<?php
$date = "2015-10-1"; //startdate
$lol = 2; //length of loan
$dates = [];
for($i = 0; $i <= ($lol + 1) ; $i++){
$rawDate = strtotime($date);
$tmpRawDate = $rawDate;
$day = date('N', $rawDate);
// check if date is sat or sun
if($day == 6 || $day == 7)
$rawDate = strtotime($date . ' +'.(8 - $day).' day');
$dates[] = date('Y-m-d', $rawDate);
$rawDate = $tmpRawDate;
$rawDate = strtotime($date . ' +1 month');
$date = date('Y-m-d', $rawDate);
}
echo '<pre>';
print_r($dates);
Demo: https://eval.in/494664
UPDATE
<?php
$date = "2015-10-1"; //startdate
$lol = 2; //length of loan
$start = strtotime($date); //startdate
$currentdate = $start;
echo "<pre>";
$titles[] = [
'Version' => 'Version 5 ',
'Date' => 'Feb-16',
'Name' => 'gary',
'RandNum' => '80',
'PaymentType' => 'P',
'dtType' => 'Q',
];
$times_table = [];
for($i = 0; $i <= ($lol + 1) ; $i++){
// store the start date in tmp variable.
$tmpStart = $start;
// get the day counter 0 for monday .. 6 for sunday
$day = date('N', $start);
$times_table[$i]['StartDate']=$date;
$times_table[$i]['Version']="v10";
// check for sat and sun, if found increment to next monday
if($day == 6 || $day == 7)
$start = strtotime(' +'.(8 - $day).' day', $start);
$times_table[$i]['DtMy']= "<strong>" . date("d-M", $start) . "</strong>";
// restore the original variable
$start = $tmpStart;
// Increment one month
$start = strtotime('+1 month', $start);
}
print_r($times_table);

Compare 2 timestamps and set a statement based on the result

I have the following table:
-------------------------------------------
|id|list_id|start_date|end_date|min_nights|
-------------------------------------------
|17| 55 |1437487200|1437735600|3|
|18| 55 |1438005600|1438167600|2|
I want to display the minimum nights for each range.
PHP:
//Seasonal Price
//1. Store all the dates between checkin and checkout in an array
$checkin_time = get_gmt_time(strtotime($checkin));
$checkout_time = get_gmt_time(strtotime($checkout));
$travel_dates = array();
$seasonal_prices = array();
$total_nights = 1;
$total_price = 0;
$is_seasonal = 0;
$i = $checkin_time;
while ($i < $checkout_time) {
$i = get_gmt_time(strtotime('+1 day', $i));
$checkin_date = date('m/d/Y', $i);
$checkin_date = explode('/', $checkin_date);
$travel_dates[$total_nights] = $checkin_date[1] . $checkin_date[0] . $checkin_date[2];
$total_nights++;
}
for ($i = 1; $i < $total_nights; $i++) {
$seasonal_prices[$travel_dates[$i]] = "";
}
//Store seasonal price of a list in an array
$seasonal_query = $this->Common_model->getTableData('seasonalprice', array('list_id' => $id));
//vaild array checked ilan
$seasonal_result = $seasonal_query->result_array();
if ($seasonal_query->num_rows() > 0) {
foreach ($seasonal_result as $time) {
//Get Seasonal price
$seasonalprice_query = $this->Common_model->getTableData(
'seasonalprice', array(
'list_id' => $id,
'start_date' => $time['start_date'],
'end_date' => $time['end_date']
));
$seasonalprice = $seasonalprice_query->row()->price;
$seasonal_min_nights = $seasonalprice_query->row()->min_nights;
//Days between start date and end date -> seasonal price
$start_time = $time['start_date'];
$end_time = $time['end_date'];
$i = $start_time;
while ($i <= $end_time) {
$start_date = date('m/d/Y', $i);
$s_date = explode('/', $start_date);
$s_date = $s_date[1] . $s_date[0] . $s_date[2];
$seasonal_prices[$s_date] = $seasonalprice;
$i = get_gmt_time(strtotime('+1 day', $i));
}
}
Then there are the following conditions:
//half-day booking functionality
//add time up to 2PM
$checkin_timestamp = get_gmt_time(strtotime($checkin)) + (14 * 60 * 60);
//add time up to 11AM
$checkout_timestamp = get_gmt_time(strtotime($checkout)) + (11 * 60 * 60);
$query = $this->db->query('SELECT id, list_id FROM `calendar` WHERE `list_id` = "' . $id . '" AND (`booked_days` BETWEEN ' . $checkin_timestamp . ' AND ' . $checkout_timestamp . ') GROUP BY `list_id`');
$rows = $query->num_rows();
$daysexist = $this->db->query("SELECT id,list_id,booked_days FROM `calendar` WHERE `list_id` = '" . $id . "' AND (`booked_days` BETWEEN " . $checkin_timestamp . " AND " . $checkout_timestamp . ") GROUP BY `list_id`");
$rowsexist = $daysexist->num_rows();
if ($rowsexist > 0) {
echo '{"available":false,"total_price":' . $data['price'] . ',"reason_message":"Those dates are not available"}';
}
if ($data['guests'] > $capacity) {
echo '{"available":false,"total_price":' . $data['price'] . ',"reason_message":"' . $capacity . ' guest(s) only allowed"}';
}
elseif ($is_seasonal == 1 && $total_nights -1 < $seasonal_min_nights) {
echo '{"available":false,"total_price":"0","reason_message":"Minimum stay is ' . $data['min_nights_seasonal'] . ' nights for the following period: '.date('m/d/Y', $start_time).' - '.date('m/d/Y', $end_time).'"}';
exit;
}
$this->session->set_userdata("total_price_'" . $id . "'_'" . $this->dx_auth->get_user_id() . "'", $data['price']);
$staggered_price = "";
if ($days >= 30) {
$staggered_price = ',"staggered_price":"' . get_currency_symbol($id) . get_currency_value1($id, $data['price']) . '","staggered":false';
}
elseif (isset($extra_guest)) {
if ($extra_guest == 1) {
echo '{"service_fee":"' . get_currency_symbol($id) . get_currency_value_lys($row->currency, get_currency_code(), $data['commission']) . '","extra_guest_price":"' . get_currency_symbol($id) . get_currency_value1($id, $extra_guest_price) . '","extra_guest":1,"reason_message":"","price_per_night":"' . get_currency_symbol($id) . get_currency_value1($id, $per_night) . '","nights":' . $days . ',"available":true,"can_instant_book":false,"total_price":"' . get_currency_symbol($id) . get_currency_value1($id, $data['price']) . '"' . $staggered_price . '}';
}
}
else {
echo '{"service_fee":"' . get_currency_symbol($id) . get_currency_value_lys($row->currency, get_currency_code(), $data['commission']) . '","reason_message":"","price_per_night":"' . get_currency_symbol($id) . get_currency_value1($id, $per_night) . '","nights":' . $days . ',"available":true,"can_instant_book":false,"total_price":"' . get_currency_symbol($id) . get_currency_value1($id, $data['price']).'"}';
}
And the condition i setted up:
elseif ($is_seasonal == 1 && $total_nights -1 < $seasonal_min_nights) {
echo '{"available":false,"total_price":"0","reason_message":"Minimum stay is ' . $data['min_nights_seasonal'] . ' nights for the following period: '.date('m/d/Y', $start_time).' - '.date('m/d/Y', $end_time).'"}';
exit;
}
And it works fine as long as i have only 1 custom range, in the database there are 2 entries. but the condition i have made always show me the last information that was added to the database instead of the information that applies for the specific timestamp range.
How would i modify the condition to meet with the timestamps and retrive the min_nights foreach timestamps range? Thanks!
I have solved it myself, looped the timestamps and in the loop i setted up the variables i need to work with, then the condition applied to each range of the timestamp individually.. If anybody have similar situation:
Getting the min_nights
$seasonal_min_nights = $seasonalprice_query->row()->min_nights;
Looping in a while:
$start_time = $time['start_date'];
$end_time = $time['end_date'];
$i = $start_time;
while ($i <= $end_time) {
$start_date = date('m/d/Y', $i);
$s_date = explode('/', $start_date);
$s_date = $s_date[1] . $s_date[0] . $s_date[2];
$seasonal_nights[$s_date] = $seasonal_min_nights;
$i = get_gmt_time(strtotime('+1 day', $i));
}
And for loop:
//Total Price
for ($i = 1; $i < $total_nights; $i++) {
$min_seasonal_nights = $seasonal_nights[$travel_dates[$i]];
$is_seasonal = 1;
}
Finally the statment:
if ($is_seasonal == 1 && $total_nights - 1 < $min_seasonal_nights) {
echo '{"available":false,"total_price":"0","reason_message":"Minimum stay is ' . $data['min_seasonal_nights'] . ' nights for the following period: ' . date('m/d/Y', $data['s_start_date']) . ' - ' . date('m/d/Y', $data['s_end_date']) . '"}';
exit;
}
I would do other stype of coding for this but had to work with the existing.. so hope it helps anybody :)

Categories