I am trying to display a number every day in a loop. After the last element is reached it needs to get to the first element again. This needs to happen daily. I have overworked my brains out but did not managed to solve it. Function needs to return current number by day/hour/minute, like . This is what I tried till now.
<?php
function recursive_daily_deals($i = 1) {
$current_date = strtotime(date('d-m-Y h:i:s'));
$dbs_date_1 = strtotime('29-06-2017 8:20:16');
$current_hour = date('h');
var_dump($current_hour);
$products = [
451,
455,
453
];
if ($i < count($products)) {
return recursive_daily_deals($i+1);
}
}
?>
EXPECTED output
> First day - June 29 2017
> It will appear 451
> Second day - June 30 2017
> It will appear 455
> 3rd day - July 1st 2017
> It will appear 453
> 4th Day - July 2nd 2017
> It will appear 453
> And start over
First you need to know how many days have been since the starting day. To do that you just need to sub the starting timestamp from the actual timestamp :
$dbs_date_1 = strtotime('29-06-2017 8:20:16');
$actualTimestamp = time();
$elapsedSec = $dbs_date_1 - $actualTimestamp;
// we need to get days from seconds
$elapsedDays = $elapsedSec / (3600*24);
$elapsedDays = floor($elapsedDays);
So when you have how many days have been since the starting day. We use floor() instead of round() because if the script runs after the half of the day it will return the number of days +1.
With this number of days we can have the number of cycles already done by dividing the number of elapsed days by the number of items in our array :
$nbItems = count($products);
$cycleCount = $elapsedDays / $nbItems;
$finishedCycles = floor($cycleCount);
We store the number of finished cycles by flooring the number of cycles. Then we just have to sub the days it took to complete those cycles from the elapsed days and we will get the position of the index.
$completeDays = $finishedCycles * $nbItems;
$actualPosition = $elapsedDays - $completeDays;
return $products[$actualPosition];
While this is a simplified version of the code originally posted, I believe it contains the kind of logic that the OP seeks, as follows:
<?php
$products = [
451,
455,
453
];
$modfactor = count($products);
$days = null;
$weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
for ($i=0, $max = 7; $i < $max; $i++) {
$days[$i] = $i % $modfactor;
}
foreach ($weekdays as $dex => $wday) {
echo "$wday, ";
echo $products[ $days[$dex] ], "\n";
}
See demo
Update: See demo here which makes use of array_map() and gets the current product ID, too.
While the loop is ever present, it is not infinite. If the number of products changes, then the modfactor changes, too. What stays constant are the days of the week. What makes the code work is taking advantage of a modulo operation.
I have a cron job that gets results from the DB to check it the interval set by user falls on today's date. I am currently thinking of doing it as below :
Get the time column for the row. Ex:2017-05-25 00:00:00
Get the frequency set. Ex:Every 2 weeks.
Get the current date in above format. Ex:2017-05-31 00:00:00
Get the difference in days. Ex:6 days.
Convert the frequency set to days. Ex:2 weeks = 14 days;
Divide (difference in time(days)) by (frequency in days). Ex:6/14
This way I will only get the result to be true when 2 weeks have passed since the time set. I.e., 14/14, 28/14, 42/14,...
If the frequency is in months, I can start dividing by 30. But somehow this feels like a hacky way of doing it. So my question is if there is better way of doing this calculation to check the difference.
This is what I have done as explained by above example.
` $frequency = ; // Get the relevant fields from db
$today = date(Y-m-d H:i:s);
foreach ($frequency as $key => $value) {
$frequency_in_days;
$frequency_type = $value->type;
$frequency_repeat = $value->repeat;
if($frequency_type == 1){
$frequency_in_days = $frequency_repeat;
} elseif($frequency_type == 2) {
$frequency_in_days = $frequency_repeat * 7;
} elseif($frequency_type == 3) {
$frequency_in_days = $frequency_repeat * 30;
} elseif($frequency_type == 4) {
$frequency_in_days = $frequency_repeat * 365;
}
// Get number of days spent between start_date and today in days.
$interval = date_diff($value->start_date, $today)->format('%a');
$result = $interval % $frequency_in_days;
if ($result == 0) {
// Frequency falls today! Do the job.
}
}`
Note: The cron job runs this script. The script again needs to check if the today falls under the frequency set.
Also for argument's sake, is this the best logic to calculate the difference?
Thank you.
This will work
Table "schedule"
`last_run` timestamp,
`frequency_seconds` int
example query for tasks that should go every two weeks:
SELECT *
FROM schedule
WHERE TIMESTAMPDIFF(last_run, NOW()) >= frequency_seconds
after fetching rows update last_run to NOW()
I have a date that goes into a loop that the user specifies. The date will always come from the database formatted as a 'Y-m-d' string. I am aware that I can compare the strings directly as long as they are in that format, however, I have also tried using strtotime to convert the dates to compare them with no luck. I am trying to determine how many paycheck a user has before a payment is due
Here is what I have
$due_date = '2016-12-13';
//count paychecks set to zero and added to by loop
$paychecks = 0;
//users next paycheck ('Y-m-d' ALWAYS)
$next_payday = $user['next_payday']; //equal to '2016-12-02'
//how often they get paid (int)
$frequency = 14;
while(strtotime($next_payday) <= strtotime($due_date)){
//next_payday equals 1480654800 when coming into the loop
//due_date equals 1481605200 when coming into the loop
//add 14 days to the date
$next_payday = date('Y-m-d', strtotime("+" .$frequency." days"));;
//add to paychecks
$paychecks++;
}
The problem is that the loop never stops. It keeps going and going.
Thanks for any help anyone can give me.
Ah, be sure to use strtotime to get integers (representing number of seconds since the epoch) for comparison and multiply your frequency of days by the number of seconds in a day (86400):
$due_date = strtotime('2016-12-25');
//count paychecks set to zero and added to by loop
$paychecks = 0;
//users next paycheck (unixtime for comparison)
$next_payday = strtotime($user['next_payday']);
//how often they get paid (int)
$frequency = 14;
while($next_payday <= $due_date){
//add 14 days to the date
$next_payday += ($frequency * 86400);
//add to paychecks
$paychecks++;
}
I am trying to populate a drop-down menu with time in 30 minute intervals (ability to change to different intervals would be nice too).
I am currently using the following code to populate the drop down (Scrounged this up online from searching around).
$sqlHours = "SELECT Open, Close FROM TimeTable";
$rsSQLHours = odbc_exec($conn, $sqlHours);
$strOpen = trim(odbc_result($rsSQLHours, "Open"));
$strClose = trim(odbc_result($rsSQLHours, "Close"));
$DeliHourOpen = substr($strOpen, 0, 2);
$DeliMinOpen = substr($strOpen, 3, 2);
$DeliHourClose = substr($strClose, 0, 2);
$DeliMinClose = substr($strClose, 3, 2);
for($hours=$DeliHourOpen; $hours<=$DeliHourClose; $hours++)
for($mins=$DeliMinOpen; $mins<60; $mins+=30)
echo '<option value='.$hours.':'.$mins.'>'.date('h:i A', strtotime($hours.':'.$mins)).'</option>'; ?>
Edit: I am storing the times in the database in 24h format, such as 08:00:00 or 22:00:00. I am using the date() just to format the displayed output in an AM/PM fashion for ease of use by users.
I am having issues when the Close Time is 20:00 it will go up to 8:30 PM in the drop-down. If I remove the = from <=$DeliHourClose then it will only display 7:30 PM. I need it to Display up to whatever the Close Time is.
The fields in the database are 'Time' in the in format 'H:i:s'.
Also, although the drop-down can be populated with a range of times from Open to Close, I need it to start at whatever the current time is + 30 minutes.
So if the Open Time is 8:00 AM, and it is 7:00 AM I want to see 8:00 AM as the first time in the drop-down. But if it is 9:00 AM, the first option in the drop-down needs to be 9:30 AM.
I have the general idea that it needs some sort of if/else to compare current time to the times in the drop-down, but I am not sure how to go about it, with the format I am using now for the drop-down.
I would prefer to have a more manageable format if possible.
Is there an easier/better way to generate a range of times with intervals that may be changed? And then populate the drop-down with the appropriate times?
Any help or suggestions would be greatly appreciated.
Using a Microsoft SQL Database.
Edit: There are multiple locations that will be stored in the table. I will add a WHERE Location = XXX clause once I get it working and add more locations to the table. Currently there is only one location, so no WHERE clause.
I am using time datatype instead of datetime as I do not want a y/m/d attached to the open/close times.
You need to generate your time stamp using time() so you can get the unix timestamp and then convert it as you wish, this way you'll be able to do time addition and add seconds straight to the given unix timestamp.
Ressource : http://fr.php.net/time
Edit : Just so we're clear and to explain it further : UNIX timestamp is the number of seconds since the 1st of january 1970, so echo time(); will return 1390934768, you just need to process it from there as the docs shows.
This code whille return this as an array : 8
8.5
9
9.5
10
10.5
11
11.5
12
12.5
13
13.5
14
14.5
15
15.5
16
16.5
17
17.5
18
18.5
19
<?php
//Function returning unix time from simple time stamp (8 or 17.5 or whatever)
function ttounix($t) {
$tunix = $t * 60 * 60;
return $tunix;
}
//Function returning simple timestamp from unix timestamp
function unixtot($u) {
$tt = $u / 60 / 60;
return $tt;
}
$gap = 30 * 60; //gap in seconds
$t1 = 8; //opening time from db
$t2 = 19; //closing time from db
//setting vars
$n = 0;
$count = array();
//Getting processed time stamps into vars
$o = ttounix($t1);
$c = ttounix($t2);
//Populating the array
while ( $o <= $c ) {
$count[$n] = $o;
$o += $gap;
$n++;
}
//Output
foreach ($count as $output) {
echo unixtot(intval($output)) . '<br />';
}
?>
I've run into a strange timewarp while doing some math with time, and it has left me stumped. Or, well, I've found the reason (or atleast a plausible one), but don't quite know what to do about it, or if there is indeed anything that can be done.
The issue in plain words is, that when adding time in larger units than 1 week (it's multipliers excluded) it seems to be impossible to be exact. And by exact I mean, that when I add 1 years worth of seconds to NOW, I end up 1 year and some hours from NOW.
I can understand that adding 1 (or more) months will do this, as a months length varies, but a year should be more or less the same, shouldn't it?
Now I know you'll want to know how I do this, so here follows (pseudoish) code:
class My_DateInterval {
public $length; // Interval length in seconds
public function __construct($interval) {
$this->length = 0;
preg_match(
'/P(((?<years>([0-9]{1,}))Y)|((?<months>([0-9]{1,}))M)|((?<weeks>([0-9]{1,}))W)|((?<days>([0-9]{1,}))D)){0,}(T((?<hours>([0-9]{1,2})){1}H){0,1}((?<minutes>([0-9]{1,2}){1})M){0,1}((?<seconds>([0-9]{1,2}){1})S){0,1}){0,1}/',
$interval, $timeparts
);
if (is_numeric($timeparts['years'])) $this->length += intval($timeparts['years']) * 31556926; // 1 year in seconds
if (is_numeric($timeparts['months'])) $this->length += intval($timeparts['months']) * 2629743.83; // 1 month in seconds
if (is_numeric($timeparts['weeks'])) $this->length += intval($timeparts['weeks']) * 604800; // 1 week in seconds
if (is_numeric($timeparts['days'])) $this->length += intval($timeparts['days']) * 86400; // 1 day in seconds
if (is_numeric($timeparts['hours'])) $this->length += intval($timeparts['hours']) * 3600; // 1 hour in seconds
if (is_numeric($timeparts['minutes'])) $this->length += intval($timeparts['minutes']) * 60; // 1 minute in seconds
if (is_numeric($timeparts['seconds'])) $this->length += intval($timeparts['seconds']);
$this->length = round($this->length);
}
}
class My_DateTime extends DateTime {
public function __construct($time, $tz = null) {
parent::__contruct($time, $tz);
}
public function add(My_DateInterval $i) {
$this->modify($i->length . ' seconds');
}
}
$d = new My_DateTime();
$i = new My_DateInterval('P1Y');
$d->add($i);
Doing some debug printouts of the interval length and before/after values show that it's all good, in the sense that "it works as expected and all checks out", but the issue stated above still stands: there is an anomaly in the exactness of it all which I'd very much would like to get right, if possible.
In so many words: How to do exact mathematics with time units greater than 1 week. (I.e. 1 month / 1 year).
PS. For those wondering why I'm using My_* classes is because PHP 5.3 just isn't widespread enough, but I'm trying to keep things in a way that migrating to built-in utility classes will be as smooth as possible.
A year is 365.25 days, roughly. Hence we have leap years.
Months have variable lengths.
Hence the semantics of what adding a year and adding a month probably don't correspond to adding a fixed number of seconds.
For example adding a month to 14th Feb 2007 would probably be expected to yield 14th March 2007 and to 14th Feb 2008 would ive 14th March 2008, adding 28 or 29 days respectively.
This stuff gets gnarly, especially when we add in different calendars, much of the world doesn't even have a February! Then add "Seven Working Days" - you need to take a public holiday calendar into account.
Are there no libraries you can find for this?
I can understand that adding 1 (or more) months will do this, as a months length varies, but a year should be more or less the same, shouldn't it?
Above, when you're adding a year's worth of seconds, you're starting with the number of days in (what I guess is) and average year (i.e., 365.2421.. * 24 * 60 * 60). So your calculation implicitly defines a year as a certain number of days.
With this definition, December 31 is a little less than 6 hours too long. So your "clock" goes from Dec 31 23:59 to 29:59 (whatever that is) before rolling over to 00:00 on January 1st. Something similar will happen with months, since you're also defining them as a certain number of seconds instead of 28 - 31 days.
If the purpose of your calculation was timing the difference between events on a generic "average" calendar, then your method will work fine. But if you need to have a correspondence with a real calendar, it's going to be off.
The simplest way to do it is to use a fake julian calendar. Keep track of each division of time (year, month, day, etc.). Define days to be 24 hours exactly. Define a year as 365 days. Add 1 day if the year is divisible by 4, but not when it's divisible by 100 unless it's also divisible by 400.
When you want to add or subtract, do the "math" manually ... every time you increment, check for "overflow". If you overflow the day of the month, reset it and increment the month (then check the month for overflow, etc., etc.).
Your calendar will be able to correspond exactly to a real calendar, for almost everything.
Most computer date implementations do basically this (to varying degrees of complexity). In javascript, for example (because my web inspector is handy):
> new Date(2010,0,1,0,0,0) - new Date(2009,0,1,0,0,0)
31536000000
As you can see, that's exactly 365 days worth of milliseconds. No mess, no fuss.
By they way, getting time right is HARD. The math is in base 60. It's all special cases (leap years, daylight savings, time zones).
Have fun.
Just in case someone is interested, the working solution was so simple it (as usual) makes me feel stupid. Instead of translating the interval length into seconds, a wordier version works correctly with PHP internals.
class My_DateInterval {
public $length; // strtotime supported string format
public $years;
public $months;
public $weeks;
public $days;
public $hours;
public $minutes;
public $seconds;
public function __construct($interval) {
$this->length = 0;
preg_match(
'/P(((?<years>([0-9]{1,}))Y)|((?<months>([0-9]{1,}))M)|((?<weeks>([0-9]{1,}))W)|((?<days>([0-9]{1,}))D)){0,}(T((?<hours>([0-9]{1,2})){1}H){0,1}((?<minutes>([0-9]{1,2}){1})M){0,1}((?<seconds>([0-9]{1,2}){1})S){0,1}){0,1}/',
$interval, $timeparts
);
$this->years = intval($timeparts['years']);
$this->months = intval($timeparts['months']);
$this->weeks = intval($timeparts['weeks']);
$this->days = intval($timeparts['days']);
$this->hours = intval($timeparts['hours']);
$this->minutes = intval($timeparts['minutes']);
$this->seconds = intval($timeparts['seconds']);
$length = $this->toString();
}
public function toString() {
if (empty($this->length)) {
$this->length = sprintf('%d years %d months %d weeks %d days %d hours %d minutes %d seconds',
$this->years,
$this->months,
$this->weeks,
$this->days,
$this->hours,
$this->minutes,
$this->seconds
);
}
return $this->length;
}
}