I want to check if a variable is greater than or equal to an item in an array.
I've tried multiple for loops, but then they just stack and stack and stack. I just need to get the dates, for example: 01-01-2005 / 01-01-2006
and compare those two both with today's date and check if today's date is greater then or equal to the date of the book. And if the book is older then today's date do some code
foreach ($user_out as $userOut) {
$userOut_id[] = $userOut['user_id'];
}
$userOut_id_implode = implode(',',$userOut_id);
//loop through each element from the tocomet able
$dateOfBook = [];
$today = date("d-m-Y");
foreach ($out as $outs) {
$datum = $outs['released'];
//gets the date of the selected book.
$bookDate = date("d-m-Y", strtotime($datum));
$dateOfBook[] = $outs['released'];
//gets the name of the author
$author_name = $outs['author'];
//gets the title of the book
$book_title = $outs['book_title'];
$today = strtotime($today);
$bookDate = strtotime($bookDate);
//checks if today is equal or smaller then the bookdate
}
$today = date("Y-m-d");
$y = count($dateOfBook);
for($x = 0; $x < $y; $x++){
echo $x;
};
if($today >= $dateOfBook($x)){
do stuff
}
$dateOfBook = [];
$today = date("d-m-Y");
$flag = 0;
foreach ($out as $outs) {
//gets the date of the book out of the database
if($today >= $outs['released']){
$flag++;
}
$dateOfBook[] = $outs['released']; # is this necessary?
}
if($flag){
# do something
}
Related
I have an array of data with a startDate variable - How would I go about returning the total number of objects with the variable of date and then just print the number?
$date = Todays date
foreach ($results->data as $row) {
$checkDate = $row->startDate;
if(date('Y-m-d', strtotime($row->startDate)) == $date){
Return total of date found
}
}
Just increment a counter whenever it is found:
$date = '2019-02-20';
$total = 0;
foreach ($results->data as $row) {
if(date('Y-m-d', strtotime($row->startDate)) == $date){
$total++; // same as $total = $total + 1;
}
}
echo "$date found $total times";
I am trying to implement the code below to force dates to skip weekends and holiday array. The weekend part is working but I am having difficulty with the holiday section, here is my code:
$holidayDates = array(
'10-10-2017', '11-10-2017'
);
$fcount = 0;
$temp = strtotime("9-10-2017");
while ($fcount < 1) {
$nextfcount = strtotime('+1 weekday', $temp);
$nextfcount2 = date('d-m-Y', $temp);
if (!in_array($nextfcount2, $holidayDates)) {
$fcount++;
}
$temp = $nextfcount;
}
$newDater = date("d-m-Y", $temp);
Let me debug this for you:
$holidayDates = array(
'10-10-2017', '11-10-2017'
);
$fcount = 0;
// 1. $temp is a terrible name for a variable
$temp = strtotime("9-10-2017");
// 2. in other words - if $fcount == 1, exit loop
while ($fcount < 1) {
// 3. $temp is now the 9th
$nextfcount = strtotime('+1 weekday', $temp);
// 4. $nextfcount2 is now the 10th
$nextfcount2 = date('d-m-Y', $temp);
if (!in_array($nextfcount2, $holidayDates)) {
// 5. Yes, found your date. $fcount is now 1
$fcount++;
}
// 6. $temp is now the 10th
$temp = $nextfcount;
// 7. $fcount is now 1, `while` condition is met, exit loop
}
// 8. The date is now the 10th
$newDater = date("d-m-Y", $temp);
You question is much too vague for me to provide you with a quality answer.
I will assume, you want to get 12-10-2017 as the result of your loop. This code will do the trick:
<?php
$holidayDates = [
'10-10-2017',
'11-10-2017',
];
$foundCounter = 0;
$theDate = strtotime("9-10-2017");
while ($foundCounter < 1) {
$theDate = strtotime('+1 weekday', $theDate);
if (!in_array(date('d-m-Y', $theDate), $holidayDates)) {
$foundCounter++;
}
}
$newDater = date("d-m-Y", $theDate);
var_dump($newDater);
// string(10) "12-10-2017"
https://3v4l.org/DcWBZ
Let's say I have an array called $selectedDates containing the following
$selectedDates = [
"2000-01-31",
"2000-02-01",
"2000-02-02",
"2000-02-20"
];
Is there some way in PHP to calculate out what # each day is consecutively.
So that the first one returns 1, the 2nd one would be returning 2, the 3rd would be 3 but the 4th would be 1 again.
I'm trying to loop through them all at the moment but am not really getitng anywhere.
<?php foreach ($selectedDates as $date): ?>
Seriously lost about what to put here.
<?php echo $consecDayCount; ?>
<?php endforeach; ?>
I'm thinking inside of the loop I may need to loop through it again? And start at the first one and check each day going up one more, adding to some incrementer for each day that says the previous date in the array was the previous day in time. I'm just kind of banging my head against a wall figuring out that part.
One way to Rome...
# We assume $selectedDates is sorted at this point.
$selectedDates = [
"2000-01-31",
"2000-02-01",
"2000-02-02",
"2000-02-20"
];
# The array we will print.
$coll = array();
# We use array_reverse to start from the last entry.
foreach(array_reverse($selectedDates) as $date) {
$tmp = $date;
$con = 1;
do $tmp = date('Y-m-d', strtotime("$tmp -1day"));
# ++$con is used to count only up if in_array gives true.
while(in_array($tmp, $selectedDates) && (++$con));
$coll[$date] = $con;
}
print_r($coll);
Result: Array ( [2000-02-20] => 1 [2000-02-02] => 3 [2000-02-01] => 2 [2000-01-31] => 1 )
Here you go:
$selectedDates = [
'2000-01-31',
'2000-02-01',
'2000-02-02',
'2000-02-20',
'2000-02-21',
];
$format = 'Y-m-d';
$consecutive = [];
$length = count($selectedDates);
$streak = false;
$last = null;
for($index = 0; $index < $length - 1; $index++) {
$firstDate = DateTime::createFromFormat($format, $selectedDates[$index]);
$secondDate = DateTime::createFromFormat($format, $selectedDates[$index + 1]);
$diff = $firstDate->diff($secondDate);
if ($diff->days === 1) {
// consecutive dates
if ($streak) {
$consecutive[$last]++; // we have another consecutive day to the current streak
} else {
$consecutive[$selectedDates[$index]] = 2; // we already have 2 consecutive days
$last = $selectedDates[$index];
$streak = true;
}
} else {
$streak = false;
}
}
var_dump($consecutive);
This will give you an array in the date => number of consecutive days starting on that date format.
Another way
$dates = array(
new DateTime('2000-01-31'),
new DateTime('2000-02-01'),
new DateTime('2000-02-02'),
new DateTime('2000-02-20'),
);
// process the array
$lastDate = null;
$ranges = array();
$currentRange = array();
foreach ($dates as $date) {
if (null === $lastDate) {
$currentRange[] = $date;
} else {
// get the DateInterval object
$interval = $date->diff($lastDate);
// DateInterval has properties for
// days, weeks. months etc. You should
// implement some more robust conditions here to
// make sure all you're not getting false matches
// for diffs like a month and a day, a year and
// a day and so on...
if ($interval->days === 1) {
// add this date to the current range
$currentRange[] = $date;
} else {
// store the old range and start anew
$ranges[] = $currentRange;
$currentRange = array($date);
}
}
// end of iteration...
// this date is now the last date
$lastDate = $date;
}
// messy...
$ranges[] = $currentRange;
// print dates
foreach ($ranges as $range) {
// there'll always be one array element, so
// shift that off and create a string from the date object
$startDate = array_shift($range);
$str = sprintf('%s', $startDate->format('D j M'));
// if there are still elements in $range
// then this is a range. pop off the last
// element, do the same as above and concatenate
if (count($range)) {
$endDate = array_pop($range);
$str .= sprintf(' to %s', $endDate->format('D j M'));
}
echo "<p>$str</p>";
} ?>
output::: Mon 31 Jan to Wed 2 Feb
Sun 20 Feb
So i have a list of weekdays in which i need to check if they are the current day. The list varies between either being 'Monday/Tuesday' and 'Wednesday - Friday'
My current solution is string comparison, so it only detects if the current weekday is written in the list item.
Heres the current solution (in PHP btw):
setlocale(LC_ALL, "danish");
$day = get_sub_field('dag'); // the field containing the user input day
$currentDay = strftime('%a', mktime());
$currentDayLower = strtolower($currentDay);
$dayLowercase = strtolower($day);
$class = '';
if(strpos($dayLowercase, $currentDayLower) !== false ){
$class = ' current-day';
} else{
$class = '';
}
I was thinking about having an array of all weekdays and comparing the user field to current day position in the array, but im not sure if that would be efficient or even possible.
Is there any obvious or alternative method that could be easier than what I'm currently doing?
Any inputs are greatly appreciated.
EDIT:
I found a working solution, which i posted as an answer (I can't choose it as the answer for 2 days though). Thanks for the inputs!
Yes, your idea is feasible and it should not affect performance badly unless you do this many times in a short period of time, where many starts at a scale of hundreds of thousands. Notice that I have created an array of $weekdays and notice that when you assign a value for $class, that is an end sign for the cycle as well.
setlocale(LC_ALL, "danish");
$day = get_sub_field('dag'); // the field containing the user input day
$dayLowercase = strtolower($day);
$weekdays = array("monday", "tuesday", "wednesday", "thursday", "friday");
$class = '';
for ($index = 0, (!$class) && ($index < 5); $index++) {
if(strpos($dayLowercase, $weekdays[$index]) !== false ){
$class = ' current-day';
} else{
$class = '';
}
}
If you want to check that the range of days includes the current day, you can do the following.
$period = 'Wednesday-Friday';
$limitDays = explode('-', $period);
$startDayName = trim(strtolower($limitDays[0]));
$endDayName = trim(strtolower($limitDays[1]));
$today = new DateTime();
$todayName = strtolower($today->format('l'));
// Check if the startDay or endDay is today.
echo "$startDayName $endDayName $todayName\n";
if ($startDayName === $todayName || $endDayName === $todayName) {
echo "Same day\n";
$class = 'current-day';
} else {
// Get a date time representing the start day.
$startDay = new \DateTime();
$startDay->modify("next $startDayName");
// Based on the start day, get the next current day.
$thisDay = new \DateTime();
$thisDay->modify("next $startDayName");
$thisDay->modify("next $todayName");
// Based on the start day, get the next end day.
$endDay = new \DateTime();
$endDay->modify("next $startDayName");
$endDay->modify("next $endDayName");
// Check if thisDay is between the startDay and endDay.
if ($startDay < $thisDay && $thisDay < $endDay) {
$class = 'current-day';
} else {
$class = '';
}
}
echo $class . "\n";
I'm not sure that this is easier or more efficient, but it's not a bad way to do this.
So as i found out, its rather complicated making a datetime from a Danish weekday string. A lot easier to go from English and format to Danish.
So i had to make it a bit different, by stitching parts of you guys' answers together.
<?php while ( have_rows('aabningstider_repeater', 'option') ) : the_row();
// vars
$day = get_sub_field('dag');
$timer = get_sub_field('aabne_timer');
$dayLower = strtolower($day);
$weekArray = array('mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag', 'søndag' );
$dayArray = preg_split('/[\s,-]+/', $dayLower);
$today = date('w') - 1;
$class = '';
if(is_array($dayArray)){
$days = [];
foreach ($dayArray as $daySingle ) {
array_push($days, array_search($daySingle, $weekArray));
}
if($today > $days[0] && $today < $days[1]){
$class = ' current-day in-between-days';
} elseif($today == $days[0] || $today == $days[1]){
$class = ' current-day';
} else{
$class = '';
}
}
endwhile; ?>
I'm pretty sure this will work untill i one day detect a major flaw. Until then it'll do.
Any feedback or optimization is greatly appreciated. And thanks for all the inputs!
setlocale(LC_ALL, "danish");
$day = get_sub_field('dag'); // the field containing the user input day
$currentDayLower = strtolower(date("D"));
$dayLowercase = strtolower($day);
$class = '';
if($dayLowercase === $currentDayLower)
$class = ' current-day';
I'm trying to find the average date and guess the next one.
The input is a list of dates that looks like this:
$completeDate = array(
'2015-04-13T00:00:00-0800',
'2015-03-20T00:00:00-0800',
'2015-02-17T00:00:00-0800',
'2015-01-10T00:00:00-0800'
);
I'm trying to scan a list of x amount of dates, and output an average of the dates overall.
So in the above example I think the output would be 2015-5-15 is expected average date.
How would I tackle this?
If you're looking for the average of those dates you can simply get the day of the year for each of those dates, average them out, and use that date:
$completeDate = array(
'2015-04-13T00:00:00-0800',
'2015-03-20T00:00:00-0800',
'2015-02-17T00:00:00-0800',
'2015-01-10T00:00:00-0800'
);
$first = null;
$last = null;
foreach($completeDate as $date) {
$dayOfYear = (new DateTime($date))->format('z');
if (is_null($first)) {
$first = $last = $dayOfYear;
}
else {
if ($dt < $first) {
$first = $dayOfYear;
}
if ($dt > $last) {
$last = $dayOfYear;
}
}
}
$avg = round(($first + $last) / 2);
$averageDate = DateTime::createFromFormat('z', $avg);
echo $averageDate->format('Y-m-d'); // 2015-02-26
Demo
If your looking for the average of the day of the month for the dates in that array and then use that day of the next month, you just need to average out the days of the month and then use that with the next month:
$completeDate = array(
'2015-04-13T00:00:00-0800',
'2015-03-20T00:00:00-0800',
'2015-02-17T00:00:00-0800',
'2015-01-10T00:00:00-0800'
);
$month = 0;
$days = 0;
foreach($completeDate as $date) {
$dt = new DateTime($date);
$month_num = $dt->format('n');
if ($month_num > $month) {
$month = $month_num;
}
$days += $dt->format('j');
}
$avg = round($days / count($completeDate));
$date = new DateTime(sprintf('%d-%01d-%01d', $dt->format('Y'), ++$month, $avg));
echo $date->format('Y-m-d'); // 2015-05-15
Demo