Make date array from multiple date range in PHP - php

I have code to select SQL Server :
<?php
include "koneksi.php";
$sql = odbc_exec($koneksi, "select * from trip");
while (odbc_fetch_row($sql)) {
$no = odbc_result($sql, "number");
$start = odbc_result($sql, "start");
$finish = odbc_result($sql,"finish");
}
?>
This loop contains the following data :
|No| Start | Finish |
|1 |2018-01-01|2018-01-05|
|2 |2018-01-10|2018-01-13|
I want to make array like this :
array(
"2018-01-01",
"2018-01-02",
"2018-01-03",
"2018-01-04",
"2018-01-05",
"2018-01-10",
"2018-01-11",
"2018-01-12",
"2018-01-13"
);
How can I create an array from this date range?
NB : looping can be more than 2 lines

For each row of the results, you can use a while() loop to add each date inside your array.
To manage date, you can use strtotime:
while (odbc_fetch_row($sql))
{
// grab our results
$start = odbc_result($sql, 'start');
$finish = odbc_result($sql, 'finish');
// convert date to timestamp
$start_tm = strtotime($start);
$finish_tm = strtotime($finish);
// add dates until $finish_tm reached
while ($start_tm < $finish_tm)
{
// push new date
$dates[] = date('Y-m-d', $start_tm);
// move date marker to next day
$start_tm = strtotime('+1 day', $start_tm);
}
}

This is an example on how to get the array:
<?php
while(odbc_fetch_row($sql)){
$no=odbc_result($sql,"number");
$start=odbc_result($sql,"start");
$finish=odbc_result($sql,"finish");
$arr = addIntoArray($arr, $start, $finish);
}
function addIntoArray($arr, $start, $end) {
$ts1 = strtotime($start);
$ts2 = strtotime($end);
for($ts=$ts1; $ts<=$ts2; $ts=$ts+86400) {
$arr[] = date('Y-m-d', $ts);
}
sort($arr);
return $arr;
}

Related

Check if any of the value in resultant array similar to values of existing array with codeigniter

I really need help to display a month list view in which deposit received month should be green in color and no-deposit month should be in red color.
I have stuck in comparing the array values. and I am using codeigniter.
I have a table with start-date and end-date by using this I have created an array to display all months in between these dates. Please find the code which I have used to do it below:
$datefrom = strtotime($showrangecalendar['chitdate_start']);
$dateto = strtotime($showrangecalendar['chitdate_end']);
$start_date = date('Y-m-d', $datefrom);
$end_date = date('Y-m-d', $dateto);
$day = 2.628e+6; // Day in Months
$format = 'Y-F'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
This code got me the Days list and I have displayed this using foreach statement to a table.
Now I have another table (accounts) with columns such as ID, Book_number, Deposit_Amount and Deposit_Month. Here the problem starts I have fetched data from "accounts" and loaded to my view using the below code from controller
$data['show_account']= $this->Accounts_model->get_all_accounts($sess_data);
My Model (Accounts_Model) is as shown below:
public function get_all_accounts($id)
{
$this->db->select("*");
$this->db->order_by('book_id','desc');
$this->db->from("accounts");
$this->db->where('bh_id',$id);
$query = $this->db->get();
return $query->result();
}
If I run the belowcode:
foreach($show_account as $values){
echo $values->deposit_month;
}
Its getting me the array result of all deposit month. Suppose I have data as 2018-Sep and 2018-Oct, These 2 months column should turn green in the above mentioned $days array.
Hope I have explained my requirement clearly. Please help me with this as I am already spent long hours in this.
Thanks in Advance.
Updated:
Now could you please check my model as follows:
public function get_dep_month($bh_id)
{
$this->db->select('deposit_month');
$this->db->from('accounts');
$this->db->where('bh_id',$_SESSION['bh_id']);
$this->db->order_by('deposit_month','asc');
$query = $this->db->get();
return $query->result_array();
}
And My Controller is as follows:
$sess_data = $this->session->userdata('bh_id');
$data['depM_array'] = $this->Accounts_model->get_dep_month($sess_data);
Now please check my View as follows:
<?php
// option 2
foreach($days as $day) { // using your already exist $day for-loop for display
if (!in_array($day, $depM_array)){
$calhilight = "calgreen";
}
else{
$calhilight = "calred";
}
?>
<li class="<?php echo $calhilight; ?>"><?= $day ?></li>
<?php
}
?>
But as my doposit_month column having only 2 values ie: 2018-Sep and 2018-Oct, Instead of getting green color for those 2 values, I am getting Green for who li element. Not getting where I have done wrong.
This is the Current page view which I am getting, Actually I am expecting a calendar view with 2 green fields for 2018-Sep and 2018-Oct and all other fields in Red
Performed Var Dumb in arrays:
Pls check this screenshot
FYI:
Below is the code from where I am getting $days array.
<?php
$datefrom = strtotime($showrangecalendar['chitdate_start']);
$dateto = strtotime($showrangecalendar['chitdate_end']);
$start_date = date('Y-m-d', $datefrom);
$end_date = date('Y-m-d', $dateto);
$day = 2.628e+6; // Day in Months
$format = 'Y-F'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
?>
Here $start_date & $end_date is fetching from another table named chitdate.
Thanks Again.
You can use array-diff or simple for-loop.
Consider the following simple example:
$days = array("2018-September", "2018-October", "2018-November", "2018-December");
$deposit_month = array("2018-September", "2018-October");
// option 1:
$diff = array_diff($days, $deposit_month);
// now $diff has: "2018-November" and "2018-December"
// option 2
foreach($days as $day) { // using your already exist $day for-loop for display
if (!in_array($day, $deposit_month))
// color in red as not found in "deposit_month"
else
// color in green
}
Nicer writing for that if can be as:
$color = in_array($day, $deposit_month) ? "Green" : "Red";

date duration between two dates excluding holidays stored in my database

I want to calculate days excluding holidays stored in my database.
But I am getting error:
Fatal error: Call to undefined function isWithinDates()
$holidays = array();
$get_holidays = mysqli_query($link,"SELECT * FROM holiday_list");
while ($fetch_holidays = mysqli_fetch_array($get_holidays)){
$holidays[]=$fetch_holidays['holiday_date'];
}
echo $begin_date = $emp_leave_data['startDate'];
echo $end_date = $last_date;
$exclude = 0;
// Loop over holidays to find out whether they are in the range
foreach ($holidays as $holiday) {
if (isWithinDates(new DateTime($holiday), $begin_date, $end_date)) {
$exclude++;
}
}
function isWithinDates(DateTime $date, DateTime $start, DateTime $end)
{
return $date >= $start && $date <= $end;
}
// Get the amount of days between our start date and the end date
// and subtract the amount of days that we know to be holidays
echo $duration = $begin_date->diff($end_date)->days - $exclude + 1;

Increment date when it should be a new month

I have a PHP script which records things based on the day. So it will have a weekly set of inputs you would enter.
I get the data correctly, but when i do $day ++; it will increment the day, going passed the end of the month without ticking the month.
example:
//12/29
//12/30
//12/31
//12/32
//12/33
Where it should look like
//12/29
//12/30
//12/31
//01/01
//01/02
My script is as follows:
$week = date ("Y-m-d", strtotime("last sunday"));
$day = $week;
$run = array(7); //this is actually defined in the data posted to the script, which is pretty much just getting the value of the array index for the query string.
foreach( $run as $key=>$value)
{
$num = $key + 1;
$items[] = "($num, $user, $value, 'run', '$day')";
echo "".$day;
$day ++;
}
Should I be manipulating the datetime differently for day incrementations?
You can use
$day = date("Y-m-d", strtotime($day . " +1 day"));
instead of
$day++;
See live demo in ideone
You refer to $day as a "datetime" but it is just a string - that is what date() returns. So when you do $day++ you are adding 1 to "2015-12-02". PHP will do everything it can to make "2015-12-02" into a number and then add 1 to it, which is not date math. Here is a simple example:
<?php
$name = "Fallenreaper1";
$name++;
echo $name
?>
This will output:
Fallenreaper2
This is how I would do it, using an appropriate data type (DateTime):
<?php
$day = new DateTime('last sunday');
$run = array(7);
foreach ($run as $key => $value) {
$num = $key + 1;
$dayStr = $day->format('Y-m-d');
$items[] = "($num, $user, $value, 'run', '$dayStr')";
echo $dayStr;
$day->modify('+1 day');
}
To increase time you should use strtotime("+1 day");
here is simple example of using it
<?php
$now_time = time();
for($i=1;$i<8;$i++) {
$now_time = strtotime("+1 day", $now_time);
echo date("Y-m-d", $now_time) . "<br>";
}
?>

How to find recursive dates in php or mysql?

I have a data like this:
$date = '01-01-2014';
$time = '15:20:00';
$location = 'New Delhi';
$recursive = '1';
.........................
......................... // other data
$recursive = 1 means weekly and 2 means monthly.
Now what i am tring to do is if recursive type is weekly then add 7 days into it till 3 months and if recursive type is monthly then add 1 month into it till 3 months.
Exa:1 $date = '01-01-2014' and $recursive = '1'
Means in above example $recursive is weekly, so get a recursive date for January, February and March.
So the expected results are:
01-01-2014, 08-01-2014, 15-01-2014, 22-01-2014, 29-01-2014 (recursiive date in january)
05-02-2014, 12-02-2014, 19-02-2014, 26-02-2014 (recursiive date in february)
05-03-2014, 12-03-2014, 19-03-2014, 26-03-2014 (recursiive date in march)
Exa 2: $date = 15-04-2014 and $recursive = 1 then get recursive date for April, May and June.
output:
15-04-2014,22-04-2014,29-04-2014 (recursive date in april)
06-05-2014,13-05-2014,20-05-2014,27-05-2014 (recursive date in may)
03-06-2014,10-06-2014,17-06-2014,24-06-2014 (recursive date in june)
Exa 3 : $date = 01-01-2014 and $recursive = 2 then get recursive date for April, May and June.
This is monthly recursive, means add 1 month into it.
output:
01-01-2014
01-02-2014 (recursiive date in february)
01-03-2014 (recursiive date in march)
then i want to insert these dates with other data into database table.
so how to achive above things? should i write logic in php or use mysql query for it?
Thanks in advance.
SIDENOTE: currently i am using this accepted answer. but now i am trying to change that.
so basically what you want to do is something like this.
//you have to have a default time zone set.. so i just did this you should already have it in your .ini file
date_default_timezone_set('America/Los_Angeles');
$date = '01-01-2014';
$time = '15:20:00';
$location = 'New Delhi';
$recursive = '1';
//set your start date and end date
$startdate = date_create($date);
$enddate = date_create($date);
$enddate = date_add($enddate,date_interval_create_from_date_string("3 months"));
//set the interval string
if($recursive == '1'){
$str = "7 days";
} else {
$str = "1 month";
}
function recursivefunc($str, $start, $end){
//if the start is equal or bigger than end pop out.
$s = date_format($start,"Y/m/d");
$e = date_format($end,"Y/m/d");
if(strtotime($s) >= strtotime($e)){
return 1;
}
echo date_format($start,"Y/m/d"), '<br>'; //print out the starting date for each loop
$newDate = date_add($start,date_interval_create_from_date_string($str)); //increment the start
recursiveFunc($str, $newDate, $end); //call the function again
}
recursiveFunc($str, $startdate, $enddate); // initial call to the function
This is how i solve it.
$date = '01-01-2014';
$location = 'New Delhi';
$start = strtotime("+2 months", strtotime($date)); //start date
$end_date = date("Y-m-t", $start); // last day of end month
$end = strtotime($end_date); //last date
/* if recursion type is weekly */
if($json['recurrence'] == "1")
{
for($dd=$start; $dd<=$end;)
{
$new_date = date('Y-m-d', $dd);
$data[] = array(
'date' => $new_date,
'location' => $location
);
$dd = strtotime("+7 day", $dd); // add 7 days
}
}
if($json['recurrence'] == "2")
{
for($dd=$start; $dd<=$end;)
{
$new_date = date('Y-m-d', $dd);
$data[] = array(
'date' => $new_date,
'location' => $location
);
$dd = strtotime("+1 month", $dd); //add 1 month
}
}
echo "<pre>";
print_r($data);

sql search whilst in a foreach loop or while loop

Hi firstly heres my code.
<?php
function getDatesBetween2Dates($startTime, $endTime) {
$day = 86400;
$format = 'd-m-Y';
$startTime = strtotime($startTime);
$endTime = strtotime($endTime);
$numDays = round(($endTime - $startTime) / $day) + 1;
$days = array();
for ($i = 0; $i < $numDays; $i++) {
$days[] = date($format, ($startTime + ($i * $day)));
}
return $days;
}
///
$days = getDatesBetween2Dates(date('d-m-Y', strtotime('-3 weeks Monday')),date('d-m-Y', strtotime('+2 weeks Sunday')));
foreach($days as $key => $value){
$dayNumber = date('d', strtotime($value));
//echo $value;
echo "<div id=\"day\">
<div id=\"number\">$dayNumber</div>";
////////////sql seearch//\\\/////////
//Connect to db
include("../djwbt.php");
$sql = "SELECT * FROM daysummary WHERE date='$value'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$place = $row['place'];
$invoicedate = $row['date'];
}
/////////////end sql search//////////
echo "<div id=\"event\">$place</div>
</div><!-- end day -->";
}
?>
What i am trying to do is show all dates between two points and for each of the dates search my db using the date as a where clause. i have tried putting the search in a few places but im not getting the right results.
this gives me the same result in each date.
e.g. 17th = (empty) as in my db, 18TH = HOME (as in my db), 19th = HOME (not as in my db), 20th = HOME (this continues all the way through fore each)
the link in each fore each works perfectly?
Any help would be amazing.
I would make one statement that gets all the needed data from your database:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
then use the foreach loop for the results
Note that mysql_ functions are deprecated, Try switching to mysqli_ or PDO

Categories