Hope all are doing well. I need to print an array as time slots.
Assume that there are 2 orders for 2021.11.15 on 11:30am to 12:00pm and 2:00pm to 4:15pm.
My order needs 1h 30m to complete. Therefore time slots should be in between 8:00am and 6:00pm skipping those times for already exist orders.
My expected results should be:
array:2 [
0 => array:2 [
"start" => "08:00:00"
"end" => "9:30:00"
]
1 => array:2 [
"start" => "09:30:00"
"end" => "11:00:00"
]
2 => array:2 [
"start" => "12:00:00"
"end" => "13:30:00"
]
3 => array:2 [
"start" => "16:15:00"
"end" => "17:45:00"
]
]
Following line is used to get exist orders object with their start and end times.
$existOrders = $this->orderHasPropartnerService->getOrderExistForDateProPartner($proPartnerDefaultLocation->id, $selectedDateRecord->date);
Then I just looped it.
if ($existOrders->count() > 0) {
$dateStartTime = $selectedDateRecord->time_from;
$x = 0;
$firstEndingTime = Carbon::parse($dateStartTime)->addMinutes($totalTimeToOrder)->format('H:i:s');
foreach ($existOrders as $key1 => $existOrder1) {
if ($existOrder1->order->time_slot_from < $firstEndingTime && $existOrder1->order->time_slot_to >= $firstEndingTime) {
$timeCheckArray[$x]['start'] = $existOrder1->order->time_slot_to;
$timeCheckArray[$x]['end'] = Carbon::parse($existOrder1->order->time_slot_to)->addMinutes($totalTimeToOrder)->format('H:i:s');
} else {
$timeSlotArray[$x]['start'] = $dateStartTime;
$timeSlotArray[$x]['end'] = $firstEndingTime;
$timeCheckArray[$x]['start'] = $firstEndingTime;
$timeCheckArray[$x]['end'] = Carbon::parse($firstEndingTime)->addMinutes($totalTimeToOrder)->format('H:i:s');
}
if (isset($existOrders[$key1+1])) {
if ($existOrders[$key1+1]->order->time_slot_from < $timeCheckArray[$x]['end'] && $existOrders[$key1+1]->order->time_slot_to >= $timeCheckArray[$x]['end']) {
} else {
$timeSlotArray[$x+1]['start'] = $timeCheckArray[$x]['start'];
$timeSlotArray[$x+1]['end'] = $timeCheckArray[$x]['end'];
}
}
}
}
As for the above example $dateStartTime will be 8:00am. Value of $totalTimeToOrder will be 1h 30m.
When I try to print $timeSlotArray it'll result as follows:
array:2 [
0 => array:2 [
"start" => "08:00:00"
"end" => "09:30:00"
]
1 => array:2 [
"start" => "08:00:00"
"end" => "09:30:00"
]
]
It is really appreciated if someone point me out where I did mistakes in this logic. Thank you so much guys for your valuable time for a problem of mine.
The best approach would be to run a for loop to check that the New order does not fall between the booked times .
Try something similar to this by converting it to a PHP Date object
$NewOrder= "4:59 pm";
$start= "5:42 am";
$end= "6:26 pm";
$date1 = DateTime::createFromFormat('h:i a', $NewOrder);
$date2 = DateTime::createFromFormat('h:i a', $start);
$date3 = DateTime::createFromFormat('h:i a', $end);
if ($date1 > $date2 && $date1 < $date3)
{
echo 'Not safe to add it ';
}
Im not great at PHP but I typed up the following code to change the header image based on the date array I have set.
Im wondering if the code looks alright and will function as intended or if iv missed something in my coding.
$hollidayevents = array(
array(
'image' => 'wp-content/uploads/1.png',
'start' => '01-02',
'end' => '02-02'
),
array(
'image' => 'wp-content/uploads/2.png',
'start' => '03-02',
'end' => '04-02'
)
);
foreach($hollidayevents as $myevent) {
if(date('d-m') >= $myevent['start'] && date('d-m') <= $myevent['end']) {
echo "<img src='".$myevent['image']."'>";
}
else { echo "<img src='wp-content/uploads/default header image'>";}
}
When you compare the dates as string with 'd-m' format the result is based on the day and only if days are same then it comes to compare months too.
For example imagine this: '20-10' > '01-11', both are with format you used 'd-m' what is the result ? First is higher then second so the result is true, even tho you would expect the opposite. Thats because only first character gets compared.
$hollidayevents = array(
array(
'image' => 'wp-content/uploads/1.png',
'start' => '02-01', // <- m-d format
'end' => '02-02' // <- m-d format
),
array(
'image' => 'wp-content/uploads/2.png',
'start' => '02-03', // <- m-d format
'end' => '02-04' // <- m-d format
)
);
$eventFound = false;
foreach($hollidayevents as $myevent) {
if(date('m-d') >= $myevent['start'] && date('m-d') <= $myevent['end']) {
echo "<img src='".$myevent['image']."'>";
$eventFound = true;
break;
}
}
if(!$eventFound){
echo "<img src='wp-content/uploads/default header image'>";
}
I have this situation:
The User can choose between 3 products, A, B or C, like showed in the image. After the user clicks one of the products, he is redirected to a register form where he must include some data, including x and y. If the selected product and the value of x and y are not right, an error is launched. If the entered data is correct, then some other actions are done. I've tried to implement this control, but I'm not sure this is the best solution.
if ($product==("A") && x < 10 && y <= 2)
{
price = 10;
}
else if ($product ==("B") && x < 50 && y <= 10 && y >2)
{
price = 20;
}
else if ($product ==("C") && x < 250 && y <=50)
{
price = 30;
}
The "object oriented" approach here would be to avoid the "tell don't ask" pattern that you implemented.
Meaning: you are "asking" for certain properties; so that your code can make a decision based on that. The solution to that is: don't do it that way!
Instead: you create a "base" product class which offers methods like isXinRange() and isYinRange(). Then you have different sub classes for each product; and AProduct.isXinRange checks x < 10 ...
Meaning: your range checks go into three different classes!
And instead of putting everything into "one" comparison, you do something like:
You create an object of AProduct for "A", BProduct for "B", ... and so on; like someProduct = generateProductFor(stringFromUser)
Then you simply ask if someProduct.isXinRange() gives you true for the X provided by the user
(I am not too familiar with PHP, so sorry for my half-pseudo-half-java coding style here)
//not a short solution or a fast one but has some advantages:
//1. has some logic shared by GhostCat but in a interative way
//2. takes in consideration of multiple cases of A,B,C... in case you load your data from DB
//3. separates raw data from logic, easy to edit later and expand
$data = array(
'A' => array(
'variables' => array(
'x' => array(
10 => '<'
),
'y' => array(
2 => '<='
),
),
'function' => 'functionA',
),
'B' => array(
'variables' => array(
'x' => array(
50 => '<'
),
'y' => array(
2 => '>'
),
),
'function' => 'functionB',
),
'C' => array(
'variables' => array(
'x' => array(
250 => '<'
),
'y' => array(
50 => '<='
),
),
'function' => 'functionC',
),
);
//
foreach ($data[$product]['variables'] as $variable => $variable_data) {
foreach ($variable_data as $number => $operator) {
switch ($operator) {
case '<':
if (!($variable < $number)) {
myFailFunction();
}
break;
case '<=':
if (!($variable <= $number)) {
myFailFunction();
}
break;
case '>':
if (!($variable < $number)) {
myFailFunction();
}
break;
}
}
}
//if no fail was met run attached function
$func_name = $data[$product]['function'];
$func_name();
//it should run like this too
//$data[$product]['function']();
I'm having a hell of a time trying to solve the following problem:
It's a calendar program where given a set of available datetime sets from multiple people, I need to figure out what datetime ranges everyone is available in PHP
Availability Sets:
p1: start: "2016-04-30 12:00", end: "2016-05-01 03:00"
p2: start: "2016-04-30 03:00", end: "2016-05-01 03:00"
p3: start: "2016-04-30 03:00", end: "2016-04-30 13:31"
start: "2016-04-30 15:26", end: "2016-05-01 03:00"
I'm looking for a function that I can call that will tell me what datetime ranges all (p) people are available at the same time.
In the above example the answer should be:
2016-04-30 12:00 -> 2016-04-30 13:31
2016-04-30 15:26 -> 2016-05-01 03:00
I did find this similar question and answer
Datetime -Determine whether multiple(n) datetime ranges overlap each other in R
But I have no idea what language that is, and have to unable to translate the logic in the answer.
Well that was fun. There's probably a more elegant way of doing this than looping over every minute, but I don't know if PHP is the language for it. Note that this currently needs to manage the start and end times to search separately, although it would be fairly trivial to calculate them based on the available shifts.
<?php
$availability = [
'Alex' => [
[
'start' => new DateTime('2016-04-30 12:00'),
'end' => new DateTime('2016-05-01 03:00'),
],
],
'Ben' => [
[
'start' => new DateTime('2016-04-30 03:00'),
'end' => new DateTime('2016-05-01 03:00'),
],
],
'Chris' => [
[
'start' => new DateTime('2016-04-30 03:00'),
'end' => new DateTime('2016-04-30 13:31')
],
[
'start' => new DateTime('2016-04-30 15:26'),
'end' => new DateTime('2016-05-01 03:00')
],
],
];
$start = new DateTime('2016-04-30 00:00');
$end = new DateTime('2016-05-01 23:59');
$tick = DateInterval::createFromDateString('1 minute');
$period = new DatePeriod($start, $tick, $end);
$overlaps = [];
$overlapStart = $overlapUntil = null;
foreach ($period as $minute)
{
$peopleAvailable = 0;
// Find out how many people are available for the current minute
foreach ($availability as $name => $shifts)
{
foreach ($shifts as $shift)
{
if ($shift['start'] <= $minute && $shift['end'] >= $minute)
{
// If any shift matches, this person is available
$peopleAvailable++;
break;
}
}
}
// If everyone is available...
if ($peopleAvailable == count($availability))
{
// ... either start a new period...
if (!$overlapStart)
{
$overlapStart = $minute;
}
// ... or track an existing one
else
{
$overlapUntil = $minute;
}
}
// If not and we were previously in a period of overlap, end it
elseif ($overlapStart)
{
$overlaps[] = [
'start' => $overlapStart,
'end' => $overlapUntil,
];
$overlapStart = null;
}
}
foreach ($overlaps as $overlap)
{
echo $overlap['start']->format('Y-m-d H:i:s'), ' -> ', $overlap['end']->format('Y-m-d H:i:s'), PHP_EOL;
}
There are some bugs with this implementation, see the comments. I'm unable to delete it as it's the accepted answer. Please use iainn or fusion3k's very good answers until I get around to fixing it.
There's actually no need to use any date/time handling to solve this
problem. You can exploit the fact that dates in this format are in alphabetical as well as chronological order.
I'm not sure this makes the solution any less complex. It's probably less
readable this way. But it's considerably faster than iterating over every minute so you might choose it if performance is a concern.
You also get to use
every
single
array
function
out there, which is nice.
Of course, because I haven't used any date/time functions, it might not work if Daylight Savings Time or users in different time zones need dealing with.
$availability = [
[
["2016-04-30 12:00", "2016-05-01 03:00"]
],
[
["2016-04-30 03:00", "2016-05-01 03:00"]
],
[
["2016-04-30 03:00", "2016-04-30 13:31"],
["2016-04-30 15:26", "2016-05-01 03:00"]
]
];
// Placeholder array to contain the periods when everyone is available.
$periods = [];
// Loop until one of the people has no periods left.
while (count($availability) &&
count(array_filter($availability)) == count($availability)) {
// Select every person's earliest date, then choose the latest of these
// dates.
$start = array_reduce($availability, function($carry, $ranges) {
$start = array_reduce($ranges, function($carry, $range) {
// This person's earliest start date.
return !$carry ? $range[0] : min($range[0], $carry);
});
// The latest of all the start dates.
return !$carry ? $start : max($start, $carry);
});
// Select each person's range which contains this date.
$matching_ranges = array_filter(array_map(function($ranges) use($start) {
return current(array_filter($ranges, function($range) use($start) {
// The range starts before and ends after the start date.
return $range[0] <= $start && $range[1] >= $start;
}));
}, $availability));
// Find the earliest of the ranges' end dates, and this completes our
// first period that everyone can attend.
$end = array_reduce($matching_ranges, function($carry, $range) {
return !$carry ? $range[1] : min($range[1], $carry);
});
// Add it to our list of periods.
$periods[] = [$start, $end];
// Remove any availability periods which finish before the end of this
// new period.
array_walk($availability, function(&$ranges) use ($end) {
$ranges = array_filter($ranges, function($range) use($end) {
return $range[1] > $end;
});
});
}
// Output the answer in the specified format.
foreach ($periods as $period) {
echo "$period[0] -> $period[1]\n";
}
/**
* Output:
*
* 2016-04-30 12:00 -> 2016-04-30 13:31
* 2016-04-30 15:26 -> 2016-05-01 03:00
*/
A different approach to your question is to use bitwise operators. The benefits of this solution are memory usage, speed and short code. The handicap is that — in your case — we can not use php integer, because we work with large numbers (1 day in minutes is 224*60), so we have to use GMP Extension, that is not available by default in most php distribution. However, if you use apt-get or any other packages manager, the installation is very simple.
To better understand my approach, I will use an array with a total period of 30 minutes to simplify binary representation:
$calendar =
[
'p1' => [
['start' => '2016-04-30 12:00', 'end' => '2016-04-30 12:28']
],
'p2' => [
['start' => '2016-04-30 12:10', 'end' => '2016-04-30 12:16'],
['start' => '2016-04-30 12:22', 'end' => '2016-05-01 12:30']
]
];
First of all, we find min and max dates of all array elements, then we init the free (time) variable with the difference in minutes between max and min. In above example (30 minutes), we obtain 230-20=1,073,741,823, that is a binary with 30 ‘1’ (or with 30 bits set):
111111111111111111111111111111
Now, for each person, we create the corresponding free-time variable with the same method. For the first person is easy (we have only one time interval): the difference between start and min is 0, the difference between end and min is 28, so we have 228-20=268435455, that is:
001111111111111111111111111111
At this point, we update global free time with a AND bitwise operation between global free time itself and person free time. The OR operator set bits if they are set in both compared values:
111111111111111111111111111111 global free time
001111111111111111111111111111 person free time
==============================
001111111111111111111111111111 new global free time
For the second person, we have two time intervals: we calculate each time interval with know method, then we compone global person free time using OR operator, that set bits if they are set in either first or second value:
000000000000001111110000000000 12:10 - 12:16
111111110000000000000000000000 12:22 - 12:30
==============================
111111110000001111110000000000 person total free time
Now we update global free time with the same method used for first person (AND operator):
001111111111111111111111111111 previous global free time
111111110000001111110000000000 person total free time
==============================
001111110000001111110000000000 new global free time
└────┘ └────┘
:28-:22 :16-:10
As you can see, at the end we have an integer with bits set only in minutes when everyone is available (you have to count starting from right). Now, you can convert back this integer to datetimes. Fortunately, GMP extension has a method to find 1/0 offset, so we can avoid to perform a for/foreach loop through all digits (that in real case are many more than 30).
Let's see the complete code to apply this concept to your array:
$calendar =
[
'p1' => [
['start' => '2016-04-30 12:00', 'end' => '2016-05-01 03:00']
],
'p2' => [
['start' => '2016-04-30 03:00', 'end' => '2016-05-01 03:00']
],
'p3' => [
['start' => '2016-04-30 03:00', 'end' => '2016-04-30 13:31'],
['start' => '2016-04-30 15:26', 'end' => '2016-05-01 03:00']
]
];
/* Get active TimeZone, then calculate min and max dates in minutes: */
$tz = new DateTimeZone( date_default_timezone_get() );
$flat = call_user_func_array( 'array_merge', $calendar );
$min = date_create( min( array_column( $flat, 'start' ) ) )->getTimestamp()/60;
$max = date_create( max( array_column( $flat, 'end' ) ) )->getTimestamp()/60;
/* Init global free time (initially all-free): */
$free = gmp_sub( gmp_pow( 2, $max-$min ), gmp_pow( 2, 0 ) );
/* Process free time(s) for each person: */
foreach( $calendar as $p )
{
$pf = gmp_init( 0 );
foreach( $p as $time )
{
$start = date_create( $time['start'] )->getTimestamp()/60;
$end = date_create( $time['end'] )->getTimestamp()/60;
$pf = gmp_or( $pf, gmp_sub( gmp_pow( 2, $end-$min ), gmp_pow( 2, $start-$min ) ) );
}
$free = gmp_and( $free, $pf );
}
$result = [];
$start = $end = 0;
/* Create resulting array: */
while( ($start = gmp_scan1( $free, $end )) >= 0 )
{
$end = gmp_scan0( $free, $start );
if( $end === False) $end = strlen( gmp_strval( $free, 2 ) )-1;
$result[] =
[
'start' => date_create( '#'.($start+$min)*60 )->setTimezone( $tz )->format( 'Y-m-d H:i:s' ),
'end' => date_create( '#'.($end+$min)*60 )->setTimezone( $tz )->format( 'Y-m-d H:i:s' )
];
}
print_r( $result );
Output:
Array
(
[0] => Array
(
[start] => 2016-04-30 12:00:00
[end] => 2016-04-30 13:31:00
)
[1] => Array
(
[start] => 2016-04-30 15:26:00
[end] => 2016-05-01 03:00:00
)
)
3v4l.org demo
Some additional notes:
At the start, we set $tz to current timezone: we will use it later, at the end, when we create final dates from timestamps. Dates created from timestamps are in UTC, so we have to set correct timezone.
To retrieve initial $min and $max values in minutes, firstly we flat original array, then we retrieve min and max date using array_column.
gmp_sub subtract second argument from first argument, gmp_pow raise number (arg 1) into power (arg 2).
In the final while loop, we use gmp_scan1 and gmp_scan0 to retrieve each ‘111....’ interval, then we create returning array elements using gmp_scan1 position for start key and gmp_scan0 position for end key.
I am trying to check if a post stored in a database is older then 1, 2, 3, and, finally, 4 days, respectively.
The table storing all of the posts has a date field. I have a query that retrieves the date and then I try to check if the date is older than 1, 2, 3 and 4 days, respectively and based on the result I want to move posts around the page.
I have the following:
foreach($this->getArticleData() as $i)
{
if(strtotime($i['date']) > strtotime('-1 day'))
{
$this->priority = '0.9';
}
elseif(strtotime($i['date']) > strtotime('-2 day'))
{
$this->priority = '0.8';
}
elseif(strtotime($i['date']) > strtotime('-3 day'))
{
$this->priority = '0.7';
}
else(strtotime($i['date']) > strtotime('-4 day'))
{
$this->priority = '0.6';
}
}
I do not think that code is working properly. In some instances the priorities are wrong. I am I using srttotime() function is is there another more reliable way to do this?
Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.
Your database uses the -'s, you're sure that's right? Anyway, a more sufficient way of your code would be:
foreach ( $this->getArticleData() as $i ) {
for ( $x = 1; $x < 10; $x++ ) {
if ( strtotime ( $i [ 'date' ] ) > strtotime ( '-'. $x ." day" ) ) {
$this->priority = '0.'. 10 - $i;
}
}
}
Flip your > around. You're checking if the date is greater/newer than the specified time. You'll also need to flip your if statement, because you're checking newest to oldest. A post that is 4 days old is also 1 day old, and will be caught by the first block.
I would prefer using a priority map and DateTime :
$list = array(
array( 'date' => '2014-12-14' ) ,
array( 'date' => '2014-12-15' ) ,
array( 'date' => '2014-12-14' ) ,
array( 'date' => '2014-12-11' ) ,
array( 'date' => '2014-12-14' ) ,
array( 'date' => '2014-12-13' ) ,
);
# maps days to priority
$priorities = array(
1 => 0.9,
2 => 0.8,
3 => 0.7,
4 => 0.6
);
$currentDate = new DateTime();
foreach( $list as $i ) {
$dateTime = new DateTime( $i['date'] );
$diff = $currentDate->diff( $dateTime );
$days = $diff->format( '%d' );
if( isset( $priorities[ $days ] ) ){
echo 'Date is: ' . $i['date'] . "| Difference is : " . $days . "| Priority is: " . $priorities[ $days ]. "<br/>";
}
}
Result:
Date is: 2014-12-14| Difference is : 1| Priority is: 0.9
Date is: 2014-12-14| Difference is : 1| Priority is: 0.9
Date is: 2014-12-11| Difference is : 4| Priority is: 0.6
Date is: 2014-12-14| Difference is : 1| Priority is: 0.9
Date is: 2014-12-13| Difference is : 2| Priority is: 0.8