How to sum time in php? - php

PHP: How to sum the result of a foreach statement?
Below is my working code. As you will see, I'm trying to count the days in each month and then sum them.
// A function to calculate days in a given month using just the date
function daysInMonths($date)
{
$month = date("m", strtotime($date));
$year = date("Y", strtotime($date));
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
return $num;
}
// A function that places the date of an unknown number of months into an array:
function getNextMonths($date, $numberOfMonths)
{
$timestamp_now = strtotime($date);
$months[] = date('Y-m-d', $timestamp_now);
for($i = 1;$i <= $numberOfMonths; $i++)
{
$months[] = date('Y-m-d', (strtotime($months[0].' +'.$i.' month')));
}
// counts the days in each month:
$j=0;
foreach ($months as $days)
{
echo "$j:".daysInMonths($days)."<br>";
++$j;
}
print_r($months);
}
getNextMonths('2011-11-1', '4');
Current output:
Array (
[0] => 2011-11-01
[1] => 2011-12-01
[2] => 2012-01-01
[3] => 2012-02-01
[4] => 2012-03-01
)
After counting:
0:30
1:31
2:31
3:29
4:31
This is all correct, I'm just having trouble summing the array after I have the days of the month counted.

$tot = 0;
foreach ($months as $days) {
$tot += daysInMonths(days);
}
echo $tot;

array_sum() - http://php.net/manual/en/function.array-sum.php
$t = array(
31,
28,
31
);
echo array_sum($t); // 90

Add a counter like you use in for while etc!!

Related

PHP array containing 12 months and start with current month and decrement

I'm trying to get an array of 12 months starting with current month, decrement and be like "Mar 2022".
This is my code:
$months = array();
$count = 0;
while ($count <= 11) {
$months[] = date('M Y', strtotime("-".$count." month"));
$count++;
}
But has some problems with months with fewer days.
For example: dd($months[0]) => "Mar 2022" and dd($months[1]) => "Mar 2022" had to be "Feb 2022".
One quick solution will as below:
<?php
$months = array();
$count = 0;
while ($count <= 11) {
$prevMonth = ($count == 1) ? "first day of previous month" : "-$count month";
$months[] = date('M Y', strtotime($prevMonth));
$count++;
}
Refrence: Getting last month's date in php
use carbon.
use Carbon\Carbon;
for ($i = 0; $i < 12; $i++) {
array_push($months, Carbon::now()->subMonth($i)->format('M Y'));
};

Group data by year, month, week and day

I have a MySQL database with sales records, what I want to do is to generate a JSON which shows all the dates between the oldest date and the most recent, and then group that info by year, month, week and day, each day will show a number (representing the quantity sold that day), if there's no data matching that date, the number should be 0.
I'm actually using PHP to solve this problem. I've tried so many solutions, but none of them seems to work.
Here's a screenshot of my query getting executed on PHPMyAdmin: https://prnt.sc/pe4twq
The final JSON should be something like this:
[
{
"year":"2019",
"months":{
"January":{
"week 1":{
"day 3":{
"total":"3400"
}
}
}
}
}
]
EDIT: Here's some code that I've tried
foreach ($rows as $row):
$date = $row['date'];
$dates[] = $date;
$first = reset($dates);
$first = strtotime($first);
$last = end($dates);
$last = strtotime($last);
$year = date('Y', strtotime($date));
$years[] = $year;
endforeach;
//86400 = 24 hours
for($i = $first; $i <= $last; $i+=86400) {
$dt = date('Y-m-d', $i);
$y = date('Y', strtotime($dt));
$m = date('n', strtotime($dt));
$w = date('W', strtotime($dt));
$d = date('D', strtotime($dt));
$allYears[] = $y;
if (in_array($dt, $dates)) {
$result[] = ['year' => $y, 'month' => $meses[$m], 'week' => $w, 'day' => $dias[$d], 'total'=>$row["total"]];
} else {
$result[] = ['year' => $y, 'month' => $meses[$m], 'week' => $w, 'day' => $dias[$d], 'total'=>"0"];
}
}
echo json_encode($result);
What I do here is I generate all the dates between the first and the last year on my database, and then I assign the total to each date, generating a JSON object for every date of every year: http://prntscr.com/pe4yjj

PHP Get recurring dates for specific weekday

How to get all recurring dates for chosen week of the day?
For example, today is Wednesday 15/02/2017 and if I choose Thursday how to get next 5 dates starting next Thursday like:
$dates = array(
[0] => "16/02/2017",
[1] => "23/02/2017",
[2] => "02/03/2017",
[3] => "09/03/2017",
[4] => "16/03/2017");
If I choose Tuesday, get dates starting 21/02/2017, which is next Tuesday
You can use strtotime to generate timestamps for this dates, the date function can generate actual dates.
<?php
// Array for dates
$dates = [];
// Get next thursday
$date = strtotime('thursday');
$dates[] = $date;
// Get the next four
for ($i = 0; $i < 4; $i++)
{
$date = strtotime('+1 week', $date);
$dates[] = $date;
}
// Echo dates
foreach ($dates as $date)
echo date('Y-m-d', $date);
Take a look at this post
Using that idea:
//Get First Thursday
$date = new DateTime();
$date->modify('next thursday');
echo "<br/>Starting Thursday: " . $date->format('d/m/Y');
//Loop over next 4 Thursdays
for($i = 2; $i <= 5; $i++)
{
$date->modify('+7 days');
echo "<br/>Thursday " . $i . ": " . $date->format('d/m/Y');
}

Generate Array of Workdays with working hours for each day

Hello I am trying to generate array which calculates all days of each month and then subtract the weekends, and after that I would like to add 8 hours for each day, so 1 = 8 , 2 = 16 etc. So far I have been able to generate the array with all days of specific month. Trying to subtract the weekends and add 8 hours for each day but no luck so far.
Here is my code:
<?php
$list=array();
$month = 1;
$year = 2017;
for($d=1; $d<=31; $d++)
{
$time=mktime(12, 0, 0, $month, $d, $year);
if (date('m', $time)==$month && ((date('D', $time) != 'Sat' || (date('D', $time) != 'Sun'))))
$list[]=date('d', $time);
}
echo "<pre>";
print_r($list);
echo "</pre>";
?>
So the final result should be something like this:
Array
(
[0][0] => 01
[0][1] => 8
[1][0] => 02
[1][1] => 16
...
)
Basically the goal is to calculate each workday how many hours should contains for a month. After having this information will be able to compare it with today date and see if working hours are completed for this month or not.
Any help is very welcome.
One way you could achieve what your after is to use DateTime to keep track of the date:
$year = 2017;
$month = 1;
$date = (new Datetime())->setDate($year, $month, 1);
$days = [];
$hours = 0;
foreach (range(1, $date->format('t')) as $i) {
$hours += $date->format('N') < 6 ? 8 : 0;
$days[] = [
'date' => $date->format('d'),
'hours' => $hours,
];
$date->modify('+1 day');
}
This is what is going on:
Set the DateTime to be the beginning of the month.
foreach(range(...)) s just another way to write for($i=1;$i<=$date->format('t');$i++). t will just give you the days in the month.
$date->format('N') < 6 is check if the day of the week is before Saturday. If so increment the $hours count by 8.
I think the rest is fairly straightforward.
Hope this helps!

Get all occurrence of specific day in a month

Suppose i have a month June 2014. Now i want to get dates of all Mondays in June month.
like Monday is coming on following days so answer will be like following
2014-06-02
2014-06-09
2014-06-16
2014-06-23
2014-06-30
please do not give be static solution only for June. I need dynamic solution for every month and purely in PHP.
Try this -
<?php
$startDate = "2014-06-01";
$endDate = "2014-06-30";
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
for($i = strtotime('Monday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
echo date('l Y-m-d', $i).PHP_EOL;
DEMO:
http://3v4l.org/n4ULA
Try to create an array with all your date with day on key (with variable $day and $date):
$array = array("Monday" => "2014-06-02", "Tuesday" => "2014-06-03", "Wednesday" => "2014-06-04");
You create a loop to reach all the result :
foreach($array as $key => $value {
if($key == "Monday")
echo $value;
}
Using the above, I created this so you can use variables to define the month, year, and selected weekday.
$month = "6";
$year = "2022";
$weekday = "Tuesday";
$d=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$first_date_of_month = $year."-".$month."-01";
$last_date_of_month = $year."-".$month."-".$d;
$startDate = strtotime($first_date_of_month);
$endDate = strtotime($last_date_of_month);
for($i = strtotime($weekday, $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
echo "<br />". date('l Y-m-d', $i).PHP_EOL;

Categories