I have a scenario where a user submits a start and stop date for a reservation in a hotel. The database has different (daily) prices for periods of the year. Given the user's date range I want to start by counting the number of days the user's range has in each range from the database and then multiplying that by the daily price for that date range.
User's dates:
03 Jun 2012 - 03 Jul 2012
Relevant date ranges from the DB
Array
(
[0] => stdClass Object
(
[date_from] => 2012-04-09
[date_to] => 2012-06-04
[price] => 44
)
[1] => stdClass Object
(
[date_from] => 2012-06-04
[date_to] => 2012-07-02
[price] => 52
)
[2] => stdClass Object
(
[date_from] => 2012-07-02
[date_to] => 2012-07-16
[price] => 61
)
)
As you can see the reservation begins in the first range, spans the second range and ends in the third range.
foreach ($dates as $key => $d)
{
$days = 0;
$user_start = strtotime($range['start']);
$user_stop = strtotime($range['stop']);
$db_start = strtotime($d->date_from);
$db_stop = strtotime($d->date_to);
if( $user_start >= $db_start && $user_stop < $db_stop )
{
$start = $range['start'];
$stop = $range['stop'];
}
elseif( $user_start <= $db_start && $user_stop > $db_start )
{
$start = $d->date_from;
$stop = $d->date_to;
}
elseif( $user_start <= $db_stop && $user_stop > $db_stop )
{
$start = $range['start'];
$stop = $d->date_to;
}
$days = calculate_nbr_days($start, $stop);
$price += $days * $d->price;
}
This code almost works, except for the fact it takes the end of the reservation ($stop) as being the last date of the DB range instead of the user's range and I can't figure out why!
Have you considered doing it all in SQL? Something this should work:
SELECT
SUM(
datediff(
IF($dateTo>date_to,date_to,$dateTo),
IF($dateFrom<date_from,date_from,$dateFrom)
) * price_per_day
) as total_cost
FROM ranges
WHERE '$dateFrom'<=date_to
AND '$dateTo'>=date_from
Related
I need to add days (input type number + input type date) but the result must be an array so I can INSERT one after another into the Database.
Here's the code (After HTML Form submitted):
<?php
$start_date = '2017-12-22';
$duration = '3';
$d = new DateTime($start_date);
$t = $d->getTimestamp();
// loop for X days
for($i=0; $i <= $duration; $i++){
// add 1 day to timestamp-
$addDay = 86400;
// get what day it is next day
$nextDay = date('w', ($t + $addDay));
// if it's Saturday or Sunday get $i-1
if($nextDay === 6 || $nextDay === 7) {
$i --;
}
// modify timestamp, add 1 day
$t = $t + $addDay;
$d->setTimestamp($t);
$day_off = $d->format( 'Y-m-d' ). "<br />";
echo $day_off;
$query = "INSERT SQL";
}
?>
From echo $day_off result I get:
2017-12-23
2017-12-24
2017-12-25
2017-12-26
Instead of 23, 24, 25, 26. I need to get the result below:
2017-12-22
2017-12-25
2017-12-26
2017-12-27
22 is the input date, start from 25 because 23 and 24 are Sat and Sun and weekends need to be excluded.
How can I achieve this result? I've been searching on the net but unfortunately, I couldn't find what I needed.
#C. Geek answer made it to works, but I have a more complex question here, since my account are not eligible to ask more question so I'll ask here.
So here's what I've tried so far (with #C. Geek answer) :
<?php
// loop for X days
for($i=0; $i < $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$day_off[] = $t;
foreach($day_off as $dayoff) {
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE `date` = '$dayoff' "));
}
$holiday[] = $data_holiday['date'];
$date = array_diff($day_off, $holiday);
$dayoff_ = $holiday;
?>
Start date : 2017-12-29
Duration : 5 days
From print_r($day_off); I'm getting this result :
Array ( [0] => 2017-12-29 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 [2] => 2018-01-02 )
And from print_r($holiday); I'm getting this result :
Array ( [0] => ) Array ( [0] => [1] => 2018-01-01 ) Array ( [0] => [1] => 2018-01-01 [2] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => [4] => )
The national date fetched from database is 2018-01-01 with 5 looping result, the final date result I need to make are 29 Dec, 02 Jan 03 Jan and 04 Jan, 05 Jan.
Any help will be much appreciated.
Thanks.
https://stackoverflow.com/a/4261223/6288442
If you are limiting to weekdays use the string weekdays.
echo date ( 'Y-m-j' , strtotime ( '3 weekdays' ) );
This should jump you ahead by 3 weekdays, so if it is Thursday it will
add the additional weekend time.
Source: http://www.php.net/manual/en/datetime.formats.relative.php
As for formatting:
http://php.net/manual/en/function.strftime.php
string strftime ( string $format [, int $timestamp = time() ] )
If you need more help with writing the code than these, please do tell in a comment
Here is my full answer:
$start_date = '2017-12-22';
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$arr[]=$t;
}
Get the holidays before the looping, then in the loop, check if date is in_array before adding it to $arr.
e.g.
$start_date = '2017-12-22';
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE YEAR(`date`) BETWEEN YEAR('$start_date') AND YEAR('$start_date')+1 "));
$holidays =
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
if(!in_array($t,$data_holiday))
$arr[]=$t;
}
FINALLY!! After several hours I fixed everything. Here's the code how I manage to skip (Sun and Monday) and also Skip the Holiday's fetched from the database (based on #C.Geek answers + several tweaking):
<?php
include 'conn.php';
$start_date = mysqli_real_escape_string($con, $_POST['start_date']);
$duration = mysqli_real_escape_string($con, $_POST['duration']);
// loop for X days
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = explode(", ", strftime("%Y-%m-%d", $d));
foreach ($t as $date) {
$to_encode = array("date" => $date);
$date_where = $to_encode['date'];
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT `date` AS '0' FROM `holiday_master_data` WHERE DATE(`date`) BETWEEN DATE('$date_where') AND DATE('$date_where') + 1 GROUP BY `id` "));
$encode_holiday = array("date" => $data_holiday[0]);
break;
}
$holiday = array_unique($encode_holiday);
$dayoff = array_diff($t, $holiday);
foreach($dayoff as $date) {
$query = mysqli_query($con, "INSERT INTO ");
if ($query) {
echo "<script>alert('Absence Saved'); window.location ='document.php' </script>";
} else {
echo "<script>alert('Gagal'); window.location ='document.php' </script>";
}
}
}
?>
Hope this helps anyone seeking the same problem I had.
Cheers.
I have a script that builds an array of week numbers for the last 12 weeks like so:
$week_numbers = range(date('W'), date('W')-11, -1);
However, if the current week number is 1, then this will return an array like so:
Array
(
[0] => 1
[1] => 0
[2] => -1
[3] => -2
[4] => -3
[5] => -4
[6] => -5
[7] => -6
[8] => -7
[9] => -8
[10] => -9
[11] => -10
)
But I need this array to look like this instead:
Array
(
[0] => 1
[1] => 52
[2] => 51
[3] => 50
[4] => 49
[5] => 48
[6] => 47
[7] => 46
[8] => 45
[9] => 44
[10] => 43
[11] => 42
)
Can anyone see a simple solution to this?
I have thought about doing something like this (not tested):
$current_week_number = date('W');
if($current_week_number<12){
// Calculate the first range of week numbers (for current year)
$this_year_week_numbers = range(date('W'), 1, -1);
// Calculate the next range of week numbers (for last year)
$last_year_week_numbers = range(52, 52-(11-$current_week_number), -1);
// Combine the two arrays to return the week numbers for the last 12 weeks
$week_numbers = array_merge($this_year_week_numbers,$last_year_week_numbers);
}else{
// Calculate the week numbers the easy way
$week_numbers = range(date('W'), date('W')-11, -1);
}
one idea
$i = 1;
while ($i <= 11) {
echo date('W', strtotime("-$i week")); //1 week ago
$i++;
}
if you arent scared of loops you can do this:
$week_numbers = range(date('W'), date('W')-11, -1);
foreach($week_numbers as $key => $value) { if($value < 1) $week_numbers[$key] += 52; }
You can do a modulo % trick:
$week_numbers = range(date('W'), date('W')-11, -1);
foreach ($week_numbers as $i => $number) {
$week_numbers[$i] = (($week_numbers[$i] + 52 - 1) % 52) + 1;
}
// -1 +1 is to change the range from 0-51 to 1-52
I've found that using modulo like this is often useful for date calculations, you can something similar for months, using 12.
Well, I think the easiest way is to create array after getting dates:
$week_numbers = array_map(function($iDay)
{
return ($iDay+52)%52?($iDay+52)%52:52;
}, range(date('W'), date('W')-11));
-note, that you can not do just % since 52%52 will be 0 (and you want 52)
I'm trying to make PHP array and here is my example.
In each array first row is unique record number "[767962]"
After inside that array hotel room id 1st row.
2nd is hotel name
3rd and 4th are first price range between
5th is the price
Array
(
[767962] => Array /// --secial id for price record--//
(
[0] => 42923 /// --hotelroomid--//
[1] => Crystal Hotels Kemer Deluxe Resort /// --Hotel Name--//
[2] => 2013-04-01 /// --Start date--//
[3] => 2013-05-16 /// --End Date--//
[4] => 179 /// --Price --//
)
[767964] => Array
(
[0] => 42923
[1] => Crystal Hotels Kemer Deluxe Resort
[2] => 2013-05-17
[3] => 2013-05-26
[4] => 239
)
[767980] => Array
(
[0] => 42940
[1] => Rixos Deluxe Resort
[2] => 2013-03-02
[3] => 2013-05-26
[4] => 340
)
)
Here is the expected output.
I would like to know total price between that hotel room 2013-05-14 - 2013-05-21
1 , 42923 , Crystal Hotels Kemer Deluxe Resort , 2013-05-14 , 2013-05-21 , 1553
2 , 42940 , Rixos Deluxe Resort , 2013-05-14 , 2013-05-21 , 2380
For example 1553 is the total price between 2013-05-14 - 2013-05-21 dates.
2013-05-14 - 179
2013-05-15 - 179
2013-05-16 - 239
2013-05-17 - 239
2013-05-18 - 239
2013-05-19 - 239
2013-05-20 - 239
2013-05-21 - 239
Total is 1553
Bro i did this kind of work in my application i think this will help you mostly but if something going wrong please let me know i will change.......
For example please refer this link for Demo;
$room_id = 42923;
$start_date = "2013-05-10 00:00:00";
$end_date = "2013-05-21 00:00:00";
find dates between above two dates
$day = 86400; // Day in seconds
$format = 'Y-m-d'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
Now for each date you need to check in which array it falls
foreach($days as $key => $d)
{
foreach($data as $key1 => $dat)
{
if($dat[0] == $room_id) {
if($d >= $dat[2] && $d<= $dat[3]) {
$amount += $dat[4];
}
}
}
}
echo $amount;
I have an array like this:
Array
(
[0] => stdClass Object
(
[Start] => 08:00
[dayName] => Tuesday
[dayID] => 2
[courseName] => Math
)
[1] => stdClass Object
(
[Start] => 10:00
[dayName] => Tuesday
[dayID] => 2
[courseName] => Geography
)
[2] => stdClass Object
(
[Start] => 14:00
[dayName] => Tuesday
[dayID] => 2
[courseName] => Science
)
[3] => stdClass Object
(
[Start] => 10:00
[dayName] => Thursday
[dayID] => 4
[courseName] => Math
)
[4] => stdClass Object
(
[Start] => 18:00
[dayName] => Friday
[dayID] => 5
[courseName] => History
)
)
What I want to do is , I want to compare the daya nd time now to the values in the array. For example lets assume that it is 7:00 am and it is Tuesday. Then I want to get the Object[0]. But if it is 11:00 o'clock then i need to get the Object[2] which starts at 14:00 on Tuesday.
It it is Tuesday and 16:00 o'clock then i need Object[3] .
If it is a weekend then i need the beginning of the week which is Tuesday at 08:00 with the Math Course.
I tried to get that using key => value but I mixed up.
How can I compare the Day and then time and in case there is a Course on that combination just pick it up if not just continue checking.
regards
littleblue
function getObject($array){
$timeNow = date('U'); // time now
$oneHour = $timeNow+3600; // time now + 1 hour
foreach($array as $num => $one){ // loop in each $array
$date = strtotime($one->Start); // convert start time to timestamp
if($date >= $timeNow && $date < $oneHour && date('l', $date) == $one->dayName){ // if all criteria met
return $array[$num]; // return that object
}
}
return array('no data'); // if no criteria is met return no data.
}
$course = getObject($yourArray);
echo $course->courseName;
You can mix the use of DateTime and a simple min search :
$myCourse = null;//initialisation
$myCourseDate =null;
$now = new DateTime;
foreach($array as $course){
//get the date from the datas
$date = DateTime::createFromFormat('l h:i',$course->dayName.' '.course->start);
if($now < $date && ($myCourseDate === null || $myCourseDate > $date)){
$myCourse = $course;
$myCourseDate = $date;
}
}
//at the end of the loop, you've got the expected course
I have an array that is produced from people wanting to reserve a time block to volunteer with our organization. I want to check to see if they chose time blocks on the same day that overlap. In my example array below the first and third elements are overlapping and I need to detect that. Any recommendation would be much appreciated:
Array
(
[0] => Array
(
[id_pc_time_blocks] => 3
[id_pc] => 2
[pc_date] => 2012-11-21
[pc_time_block] => 9:00 AM-1:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
[1] => Array
(
[id_pc_time_blocks] => 4
[id_pc] => 2
[pc_date] => 2012-11-21
[pc_time_block] => 1:00 PM-5:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 10
[pc_name] => Atlanta
)
[2] => Array
(
[id_pc_time_blocks] => 6
[id_pc] => 2
[pc_date] => 2012-11-21
[pc_time_block] => 10:00 AM-2:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
[3] => Array
(
[id_pc_time_blocks] => 6
[id_pc] => 2
[pc_date] => 2012-11-23
[pc_time_block] => 10:00 AM-2:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
[4] => Array
(
[id_pc_time_blocks] => 6
[id_pc] => 2
[pc_date] => 2012-11-23
[pc_time_block] => 3:00 AM-6:00 PM
[pc_time_block_max] => 25
[pc_time_block_count] => 0
[pc_name] => Atlanta
)
)
Not recommended for HUGE arrays, but here's a quick solution. You need to break hte times into unix time stamps for comparisson
// Run down each element of the array. (I've called it MyStartArray)
$numElements = count($MyStartArray);
for ($i=0; $i<$numElements ; $i++) {
// Calculate "Start Time" and "End Time" as Unix time stamps (use mktime function) and store as another items in the array
// You can use preg_match or substr to get the values to pump into mktime() below - not writing hte whole thing for you ;)
$MyStartArray[$i]['start_time'] = mktime( ... );
$MyStartArray[$i]['end_time'] = mktime( ... );
// Now run through all the previous elements to see if a start time is before the end time, or an end time is after the start time.
if ($i > 0) {
for ($j=0; $j<$i;$j++) {
if ($MyStartArray[$i]['start_time'] < $MyStartArray[$j]['end_time'] ||
$MyStartArray[$j]['end_time'] > $MyStartArray[$j]['start_time'] ) {
echo 'CLASH';
}
}
}
}
Here is my solution for checking each date for overlapping times. The only thing is, this is for my particular scenario and does not account for overlapping years as I dont have that need for this application.
Here is my working example:
$dateIdx = 0;
foreach($timeblocks_array as $obj) {
$timeblocks_array[$dateIdx]["intDay"] = idate("z",strtotime($obj["pc_date"]));
$timeblocks_array[$dateIdx]["intStart"] = intval($obj["start_time"]);
$timeblocks_array[$dateIdx]["intEnd"] = intval($obj["end_time"]);
$mindates[] = idate("z",strtotime($obj["pc_date"]));
$dateIdx++;
}
$minDateSingle = min($mindates);
$maxDateSingle = max($mindates);
$currentDate = $minDateSingle;
$dateIdx = 0;
while ($currentDate <= $maxDateSingle) {
$hrIndex = 0;
while ($hrIndex < 24) {
$matrixArray[$dateIdx][$hrIndex]["count"] = 0;
$matrixArray[$dateIdx][$hrIndex]["intDay"] = $currentDate;
$hrIndex++;
}
// calculate counts:
$hourIdx = 0;
foreach($matrixArray[$dateIdx] as $hour){
foreach($timeblocks_array as $block) {
if ($hour["intDay"] == $block["intDay"]) {
if ($hourIdx >= $block["intStart"] && $hourIdx < $block["intEnd"]) {
$matrixArray[$dateIdx][$hourIdx]["count"] = $matrixArray[$dateIdx][$hourIdx]["count"] + 1;
$matrixArray[$dateIdx][$hourIdx]["requests"][] = $block;
}
}
}
$hourIdx++;
}
$dateIdx++;
$currentDate = $currentDate + 1;
}
//loop through the matrix array and timeblocks array to see if they intersect
foreach($matrixArray as $day) {
$hourIdx = 0;
foreach($day as $hour) {
if ($hour["count"] > 1) {
//echo $hour["intDay"]." - Overlap on Hour $hourIdx\n";
$smarty->assign('overlappingError', 1);
$error = 1;
foreach($hour["requests"] as $overlapblock) {
//echo " --> conflict: ". $overlapblock["pc_date"]." ".$overlapblock["pc_time_block"]." (".$overlapblock["intStart"]." to ".$overlapblock["intEnd"].")\n";
}
} else if ($hour["count"] == 1) {
// these are valid hours
}
$hourIdx++;
}
}
Robbie's answer did not work for me. I found the rules that needed to be in place going off his example for just dates were:
$i[start] needs to be less than and not equal to $i[stop]
$i[start] needs to greater than and not equal to $j[stop]
$j[start] needs to be less than and not equal to $j[stop]
Therefore my solution was:
$numElements = count($dates);
for ($i=0; $i<$numElements; $i++) {
$dates[$i]['start_time'] = strtotime($dates[$i]['start']);
$dates[$i]['end_time'] = strtotime($dates[$i]['end']);
if ($i > 0) {
for ($j=0; $j<$i;$j++) {
if($dates[$i]['start_time'] >= $dates[$i]['end_time'] || $dates[$i]['start_time'] <= $dates[$j]['end_time'] || $dates[$j]['start_time'] >= $dates[$j]['end_time']) {
$this->set_error(['dates_overlap']);
$this->dates_overlap = true;
break;
}
}
}
if(isset($this->dates_overlap))
break;
}