Increment variable with number in variable + PHP - php

I have some variables like this:
$_8 = 0; $_9 = 0; $_10 = 0; $_11 = 0; $_12 = 0; $_13 = 0; $_14 = 0; $_15 = 0; $_16 = 0; $_17 = 0; $_18 = 0; $data = array();
Then I do the following:
$vistoday = $app['db']->fetchAll('SELECT `Datum Bezoek 1` FROM `psttodo-uit` WHERE CAST(`Datum Bezoek 1` AS DATE) = CURRENT_DATE AND PB = 1');
foreach($vistoday as $v){
$date = strtotime($v['Datum Bezoek 1']);
$hours = (int)date('h', $date);
$minutes = (int)date('i', $date);
if($minutes > 30)
{
$hours = $hours + 1;
$count = ${"_" . $hours} + 1;
$data[$hours] = $count;
}
else
{
$data[$hours] = ${"_" . $hours}+1;
}
}
These are the dates I pull from the database:
2014-02-27 08:25:34
2014-02-27 08:50:34
2014-02-27 08:55:34
When I output $data I get this:
array (size=2)
8 => int 1
9 => int 1
But Normally the value of key 9 should be 2. So he doesn't increment, he just adds 1 to nothing. Can somebody help me with this?

Yoг don't need variables like $_8
foreach($vistoday as $v){
$date = strtotime($v['Datum Bezoek 1']);
$hours = (int)date('h', $date);
$minutes = (int)date('i', $date);
$hours = round($hours + $minutes / 61); // if $minutes > 30 ceil else floor
$data[$hours] = isset($data[$hours]) ? $data[$hours] + 1 : 1;
}

Related

How do suptract 33 hours - 30 min in PHP [duplicate]

This question already has answers here:
Calculate difference (in hours) between two times in PHP
(2 answers)
Closed 4 months ago.
My Code is :
$hm = strtotime('33:00:00')-strtotime('00:30:00');
$hms = gmdate("H:i:s", $hm);
i need the output is 32:30:00
Use this code to get subtracted values.
$time1 = '33:00:00';
$time2 = '00:00:00';
echo 'Subtract = '.subtractTwoTimes($time1, $time2);
function subtractTwoTimes($time1, $time2){
$time1_parts = explode(':', $time1);
$time1_hours = $time1_parts[0];
$time1_mins = $time1_parts[1];
$time1_secs = $time1_parts[2];
$time2_parts = explode(':', $time2);
$time2_hours = $time2_parts[0];
$time2_mins = $time2_parts[1];
$time2_secs = $time2_parts[2];
$total_hours = $time1_hours - $time2_hours;
$total_mins = $time1_mins - $time2_mins;
$total_secs = $time1_secs - $time2_secs;
if($total_secs < 0){
$total_secs += 60;
$total_mins--;
}
if($total_mins < 0){
$total_mins += 60;
$total_hours --;
}
return $total_hours.':'.$total_mins.':'.$total_secs;
}
To get added or subtracted value from same function.
This is an edited answer. I optimized the code to make it work for you in one function.
$time1 = '33:00:00';
$time2 = '00:30:00';
echo 'Add = '. addOrSubtractTwoTimes($time1, $time2, 'add');
echo '<br>';
echo 'Subtract = '. addOrSubtractTwoTimes($time1, $time2, 'subtract');
function addOrSubtractTwoTimes($time1, $time2, $operation){
$time1_parts = explode(':', $time1);
$time1_hours = $time1_parts[0];
$time1_mins = $time1_parts[1];
$time1_secs = $time1_parts[2];
$time2_parts = explode(':', $time2);
$time2_hours = $time2_parts[0];
$time2_mins = $time2_parts[1];
$time2_secs = $time2_parts[2];
switch ($operation){
case 'add':
$total_hours = $time1_hours + $time2_hours;
$total_mins = $time1_mins + $time2_mins;
$total_secs = $time1_secs + $time2_secs;
if($total_secs > 59){
$extra_mins = floor($total_secs/60);
$total_secs = $total_secs%60;
$total_mins += $extra_mins;
}
if($total_mins > 59){
$extra_hours = floor($total_mins/60);
$total_mins = $total_mins%60;
$total_hours += $extra_hours;
}
break;
case 'subtract':
$total_hours = $time1_hours - $time2_hours;
$total_mins = $time1_mins - $time2_mins;
$total_secs = $time1_secs - $time2_secs;
if($total_secs < 0){
$total_secs += 60;
$total_mins--;
}
if($total_mins < 0){
$total_mins += 60;
$total_hours --;
}
break;
}
return sprintf('%02d', $total_hours).':'.sprintf('%02d', $total_mins).':'.sprintf('%02d', $total_secs);
}

Datetime adds an extra day

Hello in the code bellow I'm not really sure how but instead of getting 32 days it returns me 33 days.
Any advices on how to fix it seems to be because of the datetime objects or timestamps.
<?php
$pricesByMonths = [
1 => 3,
2 => 4,
3 => 3,
4 => 5,
5 => 10,
6 => 15,
7 => 20,
8 => 15,
9 => 13,
10 => 10,
11 => 8,
12 => 3,
];
$pickupDate = new DateTime('12/12/2021 19:00', new DateTimezone('UTC'));
$returnDate = new DateTime('1/13/2022 22:00', new DateTimezone('UTC'));
$initialReturnDate = $returnDate;
if($pickupDate->diff($returnDate)->d <= 1) {
$returnDate->add(new DateInterval('P1D'));
}
$pickupDateTimestamp = $pickupDate->getTimestamp();
// get pickup time
$pickup_time = date('H:i:s', $pickupDateTimestamp);
[$hours, $minutes, $seconds] = explode(':', $pickup_time);
$returnDate->setTime($hours, $minutes, $seconds);
$newReturnDate = $returnDate->getTimestamp() + 7200;
if($newReturnDate < $initialReturnDate->getTimestamp()) {
$newReturnDate += 79200;
}
$totalFee = [];
$days = 1;
$periodPrice = 15;
for ($i = $pickupDateTimestamp; $i <= $newReturnDate; $i += 3600) {
$month = date('n', $i);
if (!array_key_exists($month, $totalFee)) {
$totalFee[$month]['fee'] = $periodPrice + $pricesByMonths[$month];
$days = 1;
}
$totalFee[$month]['days'] = $days++;
}
echo '<pre>';print_r($totalFee);die;
Solved it in the end the check to force minimum 2 days was a bit wrong.
$pickupDate = new DateTime($fields['calc_pickup_date'], new DateTimezone('UTC'));
$returnDate = new DateTime($fields['calc_return_date'], new DateTimezone('UTC'));
$dateDiff = $pickupDate->diff($returnDate);
if($dateDiff->m === 0 && $dateDiff->y === 0 && $dateDiff->h === 0 && $dateDiff->d <= 1) {
$returnDate->add(new DateInterval('P1D'));
}
$pickupDateTimestamp = $pickupDate->getTimestamp();
// get pickup time
$pickup_time = $pickupDate->format('H:m:s');
[$hours, $minutes, $seconds] = explode(':', $pickup_time);
$returnDate->setTime($hours, $minutes, $seconds);
$newReturnDate = $returnDate->getTimestamp() + 7200;
if($newReturnDate <= strtotime($fields['calc_return_date'])) {
$newReturnDate += 79200;
}
$totalFee = [];
$days = 1;
$periodPrice = dpd_get_period_price($varId, $fields['order_days']);
for ($i = $pickupDateTimestamp; $i <= $newReturnDate; $i += 3600) {
$month = date('n', $i);
if (!array_key_exists($month, $totalFee)) {
$totalFee[$month]['fee'] = $periodPrice + $pricesByMonths[$month];
$days = 1;
}
$totalFee[$month]['days'] = $days++;
}

PHP Returns an Object and a Array when declaration is similar

I have a issue with the return of my multidimensional arrays. For some reason two of them are returned as objects and not arrays when the initialization is fairly the same.
I'm creating a time card and would like to return the % of time an employee was late and on time in a month for the total of past 12 months.
Code:
$eID = $_GET['showLatencyValues'];
//get the last 12 months
$month = time();
for ($i = 1; $i <= 12; $i++) {
$month = strtotime( date( 'Y-m-01' )." -$i months");
$months[] = date("r", $month);
}
$ii = 0;
for($i = 11; $i >= 0; $i--) {
$m = explode(" ", $months[$i]);
$result = $m[2].'. '.$m[3];
$last12months[$ii][0] = $ii;
$last12months[$ii][1] = $result;
$ii++;
}
//set the correct dates
$f = explode(" ", $last12months[0][1]);
$t = explode(" ", $last12months[11][1]);
$from = $f[1].'-'.letterToNumeric($f[0]).'-01';
$days = cal_days_in_month(CAL_GREGORIAN, letterToNumeric($t[0]), $t[1]); // 31
$to = $t[1].'-'.letterToNumeric($t[0]).'-'.$days;
//get the information from database
$sql = mysqli_query($conn, "SELECT DISTINCT `timeIn`,`date` FROM `clock` WHERE `eID`='$eID' AND date BETWEEN '$from' AND '$to'");
$res = mysqli_fetch_array($sql);
$break = explode("-", $res['date']);
$month = $break[1]; //set current month to
$countMonth = 0; //month number
$count = 0; //day number
$sql = mysqli_query($conn, "SELECT min(timeIn) as timeIn,`date` FROM `clock` WHERE `eID`='$eID' AND date BETWEEN '$from' AND '$to' group by date");
while($res = mysqli_fetch_array($sql)) {
$break = explode("-", $res['date']); //get the current selected month
if($month != $break[1]) { //check if current month is the same as selected by database if not then
$countMonth++; //add current month number
$count = 0; //set current day number to 0
$month = $break[1]; //set the current month to whatever is selected by database
}
$timeInData[$countMonth][$count] = $res['timeIn'];
$count++;
}
$count = 0;
for($i = 0; $i < count($timeInData); $i++) {
for($s = 0; $s < count($timeInData[$i]); $s++) {
$firstShift_timeIn = setting($conn, 'timeIn1');
$secondShift_timeIn = setting($conn, 'timeIn2');
$lateConsideredAfter = setting($conn, 'lateAfter');
$actualTime = date("H:i", strtotime($timeInData[$i][$s]));
if($res_shift['shift'] == 1) $considerLateTime = date("H:i", strtotime($firstShift_timeIn." +".$lateConsideredAfter." minutes"));
else $considerLateTime = date("H:i", strtotime($secondShift_timeIn." +".$lateConsideredAfter." minutes"));
if($actualTime > $considerLateTime) $late[$count]++;
else $onTime[$count]++;
}
$count++;
}
if($count != 12) {
$amt = (12-($count))-1;
for($w = 0; $w <= $amt; $w++) {
$onTimeYesData[$w][0] = $w;
$onTimeYesData[$w][1] = 0;
$onTimeNoData[$w][0] = $w;
$onTimeNoData[$w][1] = 0;
}
}
for($q = ($amt+1); $q <= 11; $q++) {
$total = $onTime[($q-($amt+1))] + $late[($q-($amt+1))];
$onTimeYesData[$q][0] = $q;
$onTimeYesData[$q][1] = round(($onTime[($q-($amt+1))]/$total)*100);
$onTimeNoData[$q][0] = $q;
$onTimeNoData[$q][1] = round(($late[($q-($amt+1))]/$total)*100);
}
$response[1] = $last12months;
$response[0] = $onTimeYesData;
$response[2] = $onTimeNoData;
echo json_encode($response[1])."\n\n".json_encode($response[0])."\n\n".json_encode($response[2]);
Output that I receive:
[[0,"Mar. 2019"],[1,"Apr. 2019"],[2,"May. 2019"],[3,"Jun.
2019"],[4,"Jul. 2019"],[5,"Aug. 2019"],[6,"Sep. 2019"],[7,"Oct.
2019"],[8,"Nov. 2019"],[9,"Dec. 2019"],[10,"Jan. 2020"],[11,"Feb.
2020"]]
{"1":[1,90],"2":[2,100],"3":[3,96],"4":[4,91],"5":[5,95],"6":[6,95],"7":[7,100],"8":[8,92],"9":[9,95],"10":[10,89],"11":[11,88]}
{"1":[1,10],"2":[2,0],"3":[3,4],"4":[4,9],"5":[5,5],"6":[6,5],"7":[7,0],"8":[8,8],"9":[9,5],"10":[10,11],"11":[11,13]}
I expect the two other outputs to be in the same format as the first one.
Any help is very much appreciated. Thanks.

Total days error

when start date ex:6/1/2016 and
end date ex : 8/1/2016
It is the process by computational days, so the process is the result of 3 days
6/1/2016 day
7/1/2016 day
8/1/2016 day
This is wrong .
Must be 6/1/2016 to 7/1/2016 day and 7/1/2016 to 8/1/2016 day
so the sum 2 day not 3 days
$start_date = strtotime($date_from);
$end_date = strtotime($date_to);
$datetime1 = date_create($date_from);
$datetime2 = date_create($date_to);
$interval = date_diff($datetime1, $datetime2);
$cs_booking_days = $interval->days;
// Loop between timestamps, 24 hours at a time
$total_price = '';
$adult_price = 0;
$pricings = get_option('cs_price_options');
$cs_offers_options = get_option("cs_offers_options");
$pricings_array = $pricings[$post_id];
if (isset($pricings[$post_id]['cs_plan_days'])) {
$cs_sp_days = $pricings[$post_id]['cs_plan_days'];
}
$pricing_data = array();
$brk_counter = 0;
$total_orignal = 0;
$price['total_price'] = 0;
$flag = false;
for ($i = $start_date; $i <= $end_date; $i = $i + 86400) {
$total_days++;
$brk_counter++;
$thisDate = date('Y-m-d', $i); // 2010-05-01, 2010-05-02, etc
$day = strtolower(date('D', strtotime($thisDate)));
$adult_price = $pricings_array['cs_pricing_branches']['adult_' . $day . '_price'][0];
$adult_temp_price = $adult_price != '' ? $adult_price : 0;
$adult_price = $adult_temp_price;
$to_check_date = strtotime(date('Y-m-d', $i));
<?php
// your code goes here
$startTimeStamp = strtotime("2016/01/06");
$endTimeStamp = strtotime("2016/01/08");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
echo $numberDays;
http://ideone.com/8miDiP
Back to your code => Replace
for ($i = $start_date; $i <= $end_date; $i = $i + 86400) {
this
for ($i = $start_date; $i < $end_date; $i = $i + 86400) {
<= is problem, type <
EXPLANATION
06.01 - 08.01
First loop:
$i = 06.01 and <= 08.01
Second loop:
$i = 07.01 and <= 08.01
Third loop:
$i = 08.01 and <= 08.01 - STILL TRUE, so SUM = 3 days
After change
First loop:
$i = 06.01 and < 08.01
Second loop:
$i = 07.01 and < 08.01
Third loop:
$i = 08.01 and < 08.01 - NOW FALSE, so SUM = 2 days

Sum(ADD) more than two time values in php

$time = array("18:10:00", "23:10:12", "10:05:00");
How to get the total time from this array. I need output like 51:25:12, Please help me
Try this short code:
It fill up your all case. Like as case:$a=array("18:30:00", "23:30:12", "10:05:00");.
function sum_time($array) {
$i = 0;
foreach ($array as $time) {
sscanf($time, '%d:%d:%d', $hour, $min,$sec);
$i += ($hour * 60 + $min)*60+$sec;
}
if ($h = floor($i / 3600)) {
$i %= 3600;
if ($m = floor($i / 60)) {
$i %= 60;
}
}
return sprintf('%02d:%02d:%02d', $h, $m,$i);
}
$a=array("18:30:00", "23:30:12", "10:05:00");
echo sum_time($a);
<?php
$time = array("18:10:00", "23:10:12", "10:05:00");
$hours=0;
$min=0;
$sec=0;
foreach($time as $time_array)
{
$time_exp=explode(':',$time_array);
$hours=$hours+$time_exp[0];
$min=$min+$time_exp[1];
$sec=$sec+$time_exp[2];
}
$time_output='';
$time_output=$hours.':'.$min.':'.$sec;
echo $time_output;
?>
// sample data
$time = array("18:50:00", "23:10:12", "10:05:00");
//variable initialization
$seconds = $mins = $hours = array();
//loop through all sample data items
foreach($time as $tk => $tv) {
//explode each item with seperator
$tv_parts = explode(":", $tv);
$seconds[] = $tv_parts['2'];
$mins[] = $tv_parts['1'];
$hours[] = $tv_parts['0'];
}
//add up all items respectively
$ts = array_sum($seconds);
$tm = array_sum($mins);
$th = array_sum($hours);
//adjust seconds if they are more than 59
if($ts > 59) {
$ts = $ts % 60;
$tm = $tm + floor($ts / 60);
}
//adjust minutes if they are more than 59
if($tm > 59) {
$tm = $tm % 60;
$th = $th + floor($tm / 60);
}
//padding for adjusting it to two digits when sum is below 10
$th = str_pad($th, 2, "0", STR_PAD_LEFT);
$tm = str_pad($tm, 2, "0", STR_PAD_LEFT);
$ts = str_pad($ts, 2, "0", STR_PAD_LEFT);
//final output
echo "$th:$tm:$ts";
You can refer more details about array_sum, floor and str_pad on official documentation site for PHP.
Easiest way to do this is as follows:
$time = array("18:10:00", "23:10:12", "10:05:00");
$sum="00:00:00";
$sum_new = explode(':',$sum);
foreach ($time as $t)
{
$time_new = explode(':',$t);
$sum_new[0]=$sum_new[0]+$time_new[0];
$sum_new[1]=$sum_new[1]+$time_new[1];
$sum_new[2]=$sum_new[2]+$time_new[2];
}
$sum = implode(':',$sum_new);
echo $sum;
First explode current date string via : and than just sum up parts. Don't forget to fix overflow of time parts:
function sum($times) {
$total = array(
'h' => 0,
'm' => 0,
's' => 0,
);
foreach ($times as $t) {
$timeArray = explode(":", $t);
$total['h'] += $timeArray[0];
$total['m'] += $timeArray[1];
$total['s'] += $timeArray[2];
}
if ($total['s'] >= 60) {
$total['m'] += $total['s'] % 60;
$intpart = floor($total['s']);
$total['s'] = $total['s'] - $intpart;
}
if ($total['m'] >= 60) {
$total['h'] += $total['m'] % 60;
$intpart = floor($total['m']);
$total['m'] = $total['m'] - $intpart;
}
return $total;
}
$totals = sum(array("18:10:00", "23:10:12", "10:05:00"));
echo implode(':', $totals);
Try this:
<?php
$time = array("18:10:00", "23:10:12", "10:05:00");
$seconds = 0;
foreach($time as $t)
{
$timeArr = array_reverse(explode(":", $t));
foreach ($timeArr as $key => $value)
{
if ($key > 2) break;
$seconds += pow(60, $key) * $value;
}
}
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
echo $hours.':'.$mins.':'.$secs;

Categories