php time string array - delete values for specific period - php

[0] => 12:00:00
[1] => 12:15:00
[2] => 12:30:00
[3] => 12:45:00
[5] => 13:15:00
[6] => 13:30:00
[7] => 13:45:00
[8] => 14:00:00
[9] => 14:15:00
[10] => 14:30:00
How to delete the values from above array when my starttime is "12:30:00" and endtime is "14:00:00" ? The values should be deleted are 12:30:00, 12:45:00, 13:15:00, 13:45:00 and 14:00:00

For PHP >= 5.2.0, I would do something like this:
$time_array = array('0' => '11:00:00',
'1' => '12:00:00',
'2' => '13:00:00',
'3' => '14:00:00',
'4' => '15:00:00',
'5' => '16:00:00');
echo "\nBefore:\n";
print_r($time_array);
$start = new DateTime('12:30:00');
$end = new DateTime('14:00:00');
// Magic starts here
foreach ($time_array as $key => $value) {
$datetime = new DateTime($value);
if ($datetime >= $start and $datetime <= $end)
unset($time_array[$key]);
}
// Magic finished
echo "\nAfter:\n";
print_r($time_array);
Yes, it works.

You can use this if you dont need to preserve indexes
error_reporting(E_ALL);
$array = array(
0 => '12:00:00',
1 => '12:15:00',
2 => '12:30:00',
3 => '12:45:00',
5 => '13:15:00',
6 => '13:30:00',
7 => '13:45:00',
8 => '14:00:00',
9 => '14:15:00',
10 => '14:30:00',
);
$from = '12:30:00';
$to = '14:00:00';
$filtered = array();
foreach($array as $key => $value) {
if ($value < $from || $value > $to) {
$filtered[] = $value;
}
}
var_dump($filtered);

$var_arr = array();
$time_arr = array('12:00:00','12:15:00','12:30:00','12:45:00','13:15:00',
'13:30:00','13:45:00','14:00:00','14:15:00','14:30:00');
$start = strtotime('12:30:00');
$end = strtotime('14:00:00');
foreach($time_arr as $arr):
if(strtotime($arr)<$start || strtotime($arr)>$end):
$var_arr[] = $arr;
endif;
endforeach;
print_r($var_arr);

Related

How to check some certain condition before insert operation

I have two variables which return array output and here is the example.
$scheduleRrecords:
Array
(
[0] => stdClass Object
(
[scheduleId] => 1
[ownerId] => 32
[userId] => 33
[scheduleCategoryId] => 53
[shiftTimeId] => 8
[dayPartId] => 34
[shiftBreakId] => 3
[colorCodeId] => 1
[scheduleDate] => 2017-01-02
[startTime] => 20:00:00
[endTime] => 22:00:00
[shiftNote] => Sidecar Swing
[scheduleNote] =>
[alert] => 0
[scheduleDay] => Monday
)
[1] => stdClass Object
(
[scheduleId] => 2
[ownerId] => 32
[userId] => 33
[scheduleCategoryId] => 53
[shiftTimeId] => 7
[dayPartId] => 33
[shiftBreakId] => 2
[colorCodeId] => 2
[scheduleDate] => 2017-01-02
[startTime] => 10:00:00
[endTime] => 13:00:00
[shiftNote] => Mid
[scheduleNote] =>
[alert] => 0
[scheduleDay] => Monday
)
[2] => stdClass Object
(
[scheduleId] => 3
[ownerId] => 32
[userId] => 33
[scheduleCategoryId] => 53
[shiftTimeId] => 8
[dayPartId] => 34
[shiftBreakId] => 3
[colorCodeId] => 1
[scheduleDate] => 2017-01-03
[startTime] => 20:00:00
[endTime] => 22:00:00
[shiftNote] => Sidecar Swing
[scheduleNote] =>
[alert] => 0
[scheduleDay] => Tuesday
)
[3] => stdClass Object
(
[scheduleId] => 4
[ownerId] => 32
[userId] => 33
[scheduleCategoryId] => 53
[shiftTimeId] => 7
[dayPartId] => 33
[shiftBreakId] => 3
[colorCodeId] => 2
[scheduleDate] => 2017-01-03
[startTime] => 10:00:00
[endTime] => 13:00:00
[shiftNote] => Mid
[scheduleNote] =>
[alert] => 0
[scheduleDay] => Tuesday
)
)
$checkRequestOffObj:
Array
(
[0] => stdClass Object
(
[requestOffId] => 4
[ownerId] => 32
[userId] => 33
[requestOffDate] => 2017-01-09
[dayPartId] => 33
[isPermRequest] => no
[requestOffNote] =>
[permNote] =>
[requestStatus] => pending
[approvedOrDeclinedBy] =>
[approvedOrDeclinedNote] =>
[firstName] => Erick
[lastName] => Venere
[email] => erick.portalic#gmail.com
[dayPartName] => Lunch
[status] => 1
)
[1] => stdClass Object
(
[requestOffId] => 5
[ownerId] => 32
[userId] => 33
[requestOffDate] => 2017-01-10
[dayPartId] => 33
[isPermRequest] => yes
[requestOffNote] =>
[permNote] =>
[requestStatus] => pending
[approvedOrDeclinedBy] =>
[approvedOrDeclinedNote] =>
[firstName] => Erick
[lastName] => Venere
[email] => erick.portalic#gmail.com
[dayPartName] => Lunch
[status] => 1
)
)
Now I don't want to insert records into the database with this condition:
If [isPermRequest] => no then don't insert records to that [requestOffDate] => 2017-01-09 date.
If [isPermRequest] => yes then check [requestOffDate] => 2017-01-09 day. Let's say 2017-01-09 is Monday so don't insert records to all Monday.
I have one main for loop which is used for $scheduleRrecords to loop the data and checking isPermRequest inside this loop.
Here is my core logic:
if (!empty($scheduleRrecords)) {
for ($a=0; $a<count($scheduleRrecords); $a++) {
if (isset($scheduleRrecords[$a]->ownerId) && !empty($scheduleRrecords[$a]->ownerId)) {
$aOwnerId = $scheduleRrecords[$a]->ownerId;
} else {
$aOwnerId = "";
}
if (isset($scheduleRrecords[$a]->userId) && !empty($scheduleRrecords[$a]->userId)) {
$aUserId = $scheduleRrecords[$a]->userId;
} else {
$aUserId = "";
}
if (isset($scheduleRrecords[$a]->scheduleCategoryId) && !empty($scheduleRrecords[$a]->scheduleCategoryId)) {
$aScheduleCategoryId = $scheduleRrecords[$a]->scheduleCategoryId;
} else {
$aScheduleCategoryId = "";
}
if (isset($scheduleRrecords[$a]->shiftTimeId) && !empty($scheduleRrecords[$a]->shiftTimeId)) {
$aShiftTimeId = $scheduleRrecords[$a]->shiftTimeId;
} else {
$aShiftTimeId = "";
}
if (isset($scheduleRrecords[$a]->dayPartId) && !empty($scheduleRrecords[$a]->dayPartId)) {
$aDayPartId = $scheduleRrecords[$a]->dayPartId;
} else {
$aDayPartId = "";
}
if (isset($scheduleRrecords[$a]->shiftBreakId) && !empty($scheduleRrecords[$a]->shiftBreakId)) {
$aShiftBreakId = $scheduleRrecords[$a]->shiftBreakId;
} else {
$aShiftBreakId = "";
}
if (isset($scheduleRrecords[$a]->colorCodeId) && !empty($scheduleRrecords[$a]->colorCodeId)) {
$aColorCodeId = $scheduleRrecords[$a]->colorCodeId;
} else {
$aColorCodeId = "";
}
if (isset($scheduleRrecords[$a]->scheduleDate) && !empty($scheduleRrecords[$a]->scheduleDate)) {
$aScheduleDate = $scheduleRrecords[$a]->scheduleDate;
} else {
$aScheduleDate = "";
}
if (isset($scheduleRrecords[$a]->startTime) && !empty($scheduleRrecords[$a]->startTime)) {
$aStartTime = $scheduleRrecords[$a]->startTime;
} else {
$aStartTime = "";
}
if (isset($scheduleRrecords[$a]->endTime) && !empty($scheduleRrecords[$a]->endTime)) {
$aEndTime = $scheduleRrecords[$a]->endTime;
} else {
$aEndTime = "";
}
if (isset($scheduleRrecords[$a]->shiftNote) && !empty($scheduleRrecords[$a]->shiftNote)) {
$aShiftNote = $scheduleRrecords[$a]->shiftNote;
} else {
$aShiftNote = "";
}
if (isset($scheduleRrecords[$a]->scheduleNote) && !empty($scheduleRrecords[$a]->scheduleNote)) {
$aScheduleNote = $scheduleRrecords[$a]->scheduleNote;
} else {
$aScheduleNote = "";
}
// Get next week date from scheduleDate
$getUserNextWeekArr = GlobalHelper::getUserNextWeek($aOwnerId, $aScheduleDate);
$nextDate = $getUserNextWeekArr['next'];
// Get weekly date array from selected start date
$getOwnerWeekListArr = GlobalHelper::getOwnerWeekList($aOwnerId, $copyStartDate);
// Get scheduleDate day name
$dayOfWeek = date('D', strtotime($aScheduleDate));
// Obtain The Key Of The Array
$nextDate = "";
foreach ($getOwnerWeekListArr as $key => $val) {
if ($val['day'] == $dayOfWeek) {
$nextDate .= $getOwnerWeekListArr[$key]['date'];
}
}
$scheduleDate = str_replace('/', '-', date('Y-m-d', strtotime($nextDate)));
$checkRequestOffObj = GlobalHelper::checkRequestOff($aOwnerId, $aUserId, $aDayPartId, $scheduleDate);
}
}
Here is my login but it's not working:
if (!empty($checkRequestOffObj)) {
for ($t=0; $t<count($checkRequestOffObj); $t++) {
$tRequestOffDate = $checkRequestOffObj[$t]->requestOffDate;
$tRequestOffDay = date('D', strtotime($checkRequestOffObj[$t]->requestOffDate));
$tDayPartId = $checkRequestOffObj[$t]->dayPartId;
if ($checkRequestOffObj[$t]->isPermRequest == 'yes') {
if ($dayOfWeek == $tRequestOffDay && $aDayPartId != $tDayPartId) {
$result = DB::table('schedules')
->where('ownerId', '=', $aOwnerId)
->where('userId', '=', $aUserId)
->where('scheduleCategoryId', '=', $aScheduleCategoryId)
->where('shiftTimeId', '=', $aShiftTimeId)
->where('dayPartId', '=', $aDayPartId)
->where('shiftBreakId', '=', $aShiftBreakId)
->where('colorCodeId', '=', $aColorCodeId)
->where('scheduleDate', '=', $scheduleDate)
->exists();
if ($result == ""):
DB::table('schedules')->insert(
array(
'ownerId' => $aOwnerId,
'userId' => $aUserId,
'scheduleCategoryId' => $aScheduleCategoryId,
'shiftTimeId' => $aShiftTimeId,
'dayPartId' => $aDayPartId,
'shiftBreakId' => $aShiftBreakId,
'colorCodeId' => $aColorCodeId,
'scheduleDate' => $scheduleDate,
'startTime' => $aStartTime,
'endTime' => $aEndTime,
'shiftNote' => $aShiftNote,
'scheduleNote' => $aScheduleNote,
'createdBy' => Auth::user()->userId,
'isPosted' => "0",
'sendSchedule' => "0",
'cronStatus' => "0",
)
);
endif;
} else {
continue;
}
} else {
if ($aDayPartId != $tDayPartId && $scheduleDate == $tRequestOffDate) {
$result = DB::table('schedules')
->where('ownerId', '=', $aOwnerId)
->where('userId', '=', $aUserId)
->where('scheduleCategoryId', '=', $aScheduleCategoryId)
->where('shiftTimeId', '=', $aShiftTimeId)
->where('dayPartId', '=', $aDayPartId)
->where('shiftBreakId', '=', $aShiftBreakId)
->where('colorCodeId', '=', $aColorCodeId)
->where('scheduleDate', '=', $scheduleDate)
->exists();
if ($result == ""):
DB::table('schedules')->insert(
array(
'ownerId' => $aOwnerId,
'userId' => $aUserId,
'scheduleCategoryId' => $aScheduleCategoryId,
'shiftTimeId' => $aShiftTimeId,
'dayPartId' => $aDayPartId,
'shiftBreakId' => $aShiftBreakId,
'colorCodeId' => $aColorCodeId,
'scheduleDate' => $scheduleDate,
'startTime' => $aStartTime,
'endTime' => $aEndTime,
'shiftNote' => $aShiftNote,
'scheduleNote' => $aScheduleNote,
'createdBy' => Auth::user()->userId,
'isPosted' => "0",
'sendSchedule' => "0",
'cronStatus' => "0",
)
);
endif;
} else {
continue;
}
}
}
} else {
}
Any Idea how to check before insert operation?
Thanks.

how to get interval overlap between time and given multiple time?

i have below array
Array
(
[0] => Array
(
[from_time] => 15:00
[to_time] => 17:15
)
[1] => Array
(
[from_time] => 10:00
[to_time] => 12:15
)
[2] => Array
(
[from_time] => 09:00
[to_time] => 11:15
)
[3] => Array
(
[from_time] => 09:00
[to_time] => 11:15
)
[4] => Array
(
[from_time] => 14:00
[to_time] => 16:15
)
[5] => Array
(
[from_time] => 15:00
[to_time] => 17:15
)
)
i want to get common time in this array.
If i Find common time in this array my expected result should be
Array
(
[0] => Array
(
[from_time] => 10:00
[to_time] => 11:15
)
[1] => Array
(
[from_time] => 15:00
[to_time] => 16:15
)
)
I have try with below code but not getting accurate result.
foreach ($booking_time as $time1) {
foreach ($booking_time as $time2) {
{
if(($time1['from_time'] > $time2['from_time'] && $time1['from_time'] < $time2['to_time'])|| ( $time1['to_time'] > $time2['from_time'] && $time1['to_time'] < $time2['to_time'])){
echo $time1['from_time'];
echo $time1['to_time'];
}
}
}
}
Quick example (I think it can be shorter, but for quick understanding it is ok) :
$intervals = [
['from_time' => '15:00', 'to_time' => '17:15'],
['from_time' => '10:00', 'to_time' => '12:15'],
['from_time' => '09:00', 'to_time' => '11:15'],
['from_time' => '09:00', 'to_time' => '11:15'],
['from_time' => '14:00', 'to_time' => '16:15'],
['from_time' => '15:00', 'to_time' => '17:15'],
];
$overlaps = [];
foreach ($intervals as $interval) {
$key = null;
foreach ($overlaps as $_key => $_intervals) {
foreach ($_intervals as $_interval) {
if (
($_interval['from_time'] <= $interval['from_time'] && $interval['from_time'] <= $_interval['to_time'])
||
($_interval['from_time'] <= $interval['to_time'] && $interval['to_time'] <= $_interval['to_time'])
) {
$key = $_key;
break 2;
}
}
}
if (is_null($key)) {
$key = count($overlaps);
}
$overlaps[$key][] = $interval;
}
foreach ($overlaps as &$overlap) {
$from = '00:00';
$to = '23:59';
foreach ($overlap as $_interval) {
$from = max($from, $_interval['from_time']);
$to = min($to, $_interval['to_time']);
}
$overlap = ['from_time' => $from, 'to_time' => $to];
}
unset($overlap);
print_r($overlaps);
Output :
Array
(
[0] => Array
(
[from_time] => 15:00
[to_time] => 16:15
)
[1] => Array
(
[from_time] => 10:00
[to_time] => 11:15
)
)
General Overlay for comparing A and B
X) A(start) < B(start) < A(end) < B(end)
Y) B(start) < A(start) < B(end) < A(end)
(and usually full inclusions are required as well)
B(start) <= A(start) < A(end) <= B(end)
A(start) <= B(start) < B(end) <= A(end)
You actually wrote that down, but you overlooked that A and B are switching places in your source (A will be B and B A at another run -> you only need to check X or Y) and depending on which case you check you have to adjust your variable/key selection.
Additionally you are not handling inclusions well (exluding them or appropriately including them).
Simple example:
a = 10-20
b = 15-25
you would expect 15-20 as result
lets assume the run: time1 a, time2 b
$time1['to_time'] > $time2['from_time'] &&
$time1['to_time'] < $time2['to_time']
matches and prints
10-20 (time1 (a) from and to -- you wanted to print time2 from and time1 to)
another run will assign: time2 a and time1 b
$time1['from_time'] > $time2['from_time'] &&
$time1['from_time'] < $time2['to_time'])
matches and prints
15-25 (time1 (b) from and to -- you wanted to print time1 from and time2 to)
Here a working example
foreach($array as $key => $time1) {
foreach($array as $key2 => $time2) {
if (($time1["from_time"] < $time2["from_time"]) && ($time2["from_time"] < $time1["to_time"]) && ($time2["to_time"] > $time1["to_time"])) {
$overlap[] = array("from_key" => $time2["from_time"], "to_time" => $time1["to_time"]);
}
//inclusion
if (($time1["from_time"] >= $time2["from_time"]) && ($time2["to_time"] >= $time1["to_time"]) && ($key !== $key2)) {
$overlap[] = array("from_time" => $time1["from_time"], "to_time" => $time1["to_time"]);
}
}
}
Disclaimer: There are no checks for double entries. If you dont want inclusions you need a way to handle A(start) < B(start) < A(end) == B(end) etc.
you wanna increment or += [any number]
$latest = aray_pop($booking_time); // this will grab the last element from the array
for($i = 0; $i < $latest; $i += 15 // this is the number you want to increment by) {
$booking_time[$key] = $i;
}

weekly series calculation with php if statement

I am a little array-ed out with this and I am hoping that someone can help me. I have a few variables and am a little stuck with using the arrays in an if statement.
What I like to find out is if my relocation_date is less then notified_time (from a generated series) then give me old_meter_id else meter_id
$meter_id = 1393;
$notified_time = '2013-05-01 09:53';
$completed_time = '2013-05-01 11:52';
$relocation_date = '2013-04-24 00:00';
$old_meter_id = 1832;
$notified_time = strtotime($notified_time);
$completed_time = strtotime($completed_time);
$relocation_date = date($relocation_date);
$combined = array();
for($i=0;$i<=10;$i++)
{
$start_series = strtotime("- $i weeks", $notified_time);
$end_series = strtotime("- $i weeks", $completed_time);
$combined[] = array( 'start_time' => date('d-m-Y H:i:s',$start_series),
'end_time' => date('d-m-Y H:i:s',$end_series),
'relocation' => $relocation_date,
'meter_id' => $meter_id,
'old_meter_id' => $old_meter_id,
);
}
sample expected output to be like:
Array
(
[0] => Array
(
[start_time] => 01-05-2013 09:53:00
[end_time] => 01-05-2013 11:52:00
[relocation] => 2013-04-24 00:00
[meter_id] => 1393
)
[1] => Array
(
[start_time] => 24-04-2013 09:53:00
[end_time] => 24-04-2013 11:52:00
[relocation] => 2013-04-24 00:00
[meter_id] => 1832
)
.....
Thanks in advance!
You can check it in the loop like
for($i=0;$i<=10;$i++)
{
$start_series = strtotime("- $i weeks", $notified_time);
$end_series = strtotime("- $i weeks", $completed_time);
if(strtotime($relocation_date) < $start_series){
$combined[] = array( 'start_time' => date('d-m-Y H:i:s',$start_series),
'end_time' => date('d-m-Y H:i:s',$end_series),
'relocation' => $relocation_date,
'meter_id' =>$old_meter_id,
);
}else{
$combined[] = array( 'start_time' => date('d-m-Y H:i:s',$start_series),
'end_time' => date('d-m-Y H:i:s',$end_series),
'relocation' => $relocation_date,
'meter_id' =>$meter_id,
);
}
}
Hope this is the solution you are looking for

Check PHP array for consecutive indexes

Sorry if the title of the question is unclear, I couldn't sum it up more precisely.
This is the issue:
To begin with, I have an array in this format:
Array (
[0] => 09:00
[1] => 10:00
[2] => 11:00
[3] => 12:00
[4] => 13:00
[5] => 14:00
[6] => 15:00
[7] => 16:00
[8] => 17:00
[9] => 18:00
)
Then some of the members are unset, so after that we're left with something like:
Array (
[0] => 09:00
[1] => 10:00
[6] => 15:00
[7] => 16:00
[8] => 17:00
[9] => 18:00
)
As you see, the array represents time slots. Now, what I need to do is eliminate all time slots shorter than 3 hours. So I need to go through the array and, wherever there are less than 3 members of the original array present, take them out too. So in the example above, since 09:00 and 10:00 are not followed by 11:00, I need to take them out and be left with:
Array (
[6] => 15:00
[7] => 16:00
[8] => 17:00
[9] => 18:00
)
How do I accomplish this? Logically, I think it might be easiest to check for 3 consecutive indexes, rather then checking the actual times but I'm open to any suggestions.
I've solved the problem on my own, and I made it generic so it would work for any duration, not just 3 hours.
$dur=3; //could be anything
foreach($work_times as $member){
$key=array_search($member,$work_times);
$a_ok=0;
for($options=0;$options<$dur;$options++){
$thisone=1;
for($try=$key-$options;$try<$key-$options+$dur;$try++){
if(!array_key_exists($try,$work_times))
$thisone=0;
}
if($thisone==1)
$a_ok=1;
}
if($a_ok==0)
unset($work_times[$key]);
}
$arr = array(
0 => '09:00',
1 => '10:00',
6 => '15:00',
7 => '16:00',
8 => '17:00',
9 => '18:00'
);
// for some testing
$arr += array(12 => '19:00', 13 => '20:00', 14 => '21:00');
$arr += array(16 => '22:00', 17 => '23:00');
$dontRemove = array();
foreach($arr as $key => $val) {
// if the next 2 keys are set
if (isset($arr[$key+1]) && isset($arr[$key+2])) {
$dontRemove[] = $key;
$dontRemove[] = $key+1;
$dontRemove[] = $key+2;
}
}
// combine and diff the keys to get the keys which should be actually removed
$remove = array_diff(array_keys($arr), array_unique($dontRemove));
foreach($remove as $key) {
unset($arr[$key]);
}
print_r($arr);
Try this:
<?php
function check() {
global $array;
$tmpArr = array_keys( $array );
$val1 = $tmpArr[0];
$val2 = $tmpArr[1];
$val3 = $tmpArr[2];
if( ( ++$val1 == $val2 ) && ( ++$val2 == $val3 ) ) {
// continuous
} else {
// not continuous, remove it
unset( $array[$tmpArr[0]] );
}
}
$array = array(
'0' => '09:00',
'1'=> '10:00',
'6' => '15:00',
'7'=> '16:00',
'8' => '17:00',
'9' => '18:00'
);
$total = count( $array );
$ctotal = 0;
while( $ctotal < $total ) {
if( count( $array ) <= 2 ) {
// this array has 2 elements left, which obviously
// nullifies the 3 continuous element check
$array = array();
break;
} else {
//check the array backwards
check();
$total--;
}
}
?>
Hope this helps
$a = Array(
0 => "09:00",
1 => "10:00",
6 => "15:00",
7 => "16:00",
8 => "17:00",
9 => "18:00",
11 => "20:00",
);
foreach ($a as $k => $v) {
// previous or next two time slots exist
$consecutive = (isset($a[$k-1]) or
(isset($a[$k+1]) and isset($a[$k+2])));
if (!$consecutive)
unset($a[$k]);
}

how to generate monthly days with PHP?

Im trying to generate days of the current month like this
$year = date('Y');
$month = date('m');
$dayCount = cal_days_in_month(CAL_GREGORIAN,$month,$year);
for ($i = 1; $i <= $dayCount; $i++)
{
$tree_data->data[$i] = $year."-".$month."-".$i;
}
print "<pre>";
print_r($tree_data);
which gives me output like
stdClass Object
(
[data] => Array
(
[1] => 2011-12-1
[2] => 2011-12-2
[3] => 2011-12-3
[4] => 2011-12-4
[5] => 2011-12-5
[6] => 2011-12-6
[7] => 2011-12-7
[8] => 2011-12-8
[9] => 2011-12-9
[10] => 2011-12-10
[11] => 2011-12-11
[12] => 2011-12-12
[13] => 2011-12-13
[14] => 2011-12-14
[15] => 2011-12-15
[16] => 2011-12-16
[17] => 2011-12-17
[18] => 2011-12-18
[19] => 2011-12-19
[20] => 2011-12-20
[21] => 2011-12-21
[22] => 2011-12-22
[23] => 2011-12-23
[24] => 2011-12-24
[25] => 2011-12-25
[26] => 2011-12-26
[27] => 2011-12-27
[28] => 2011-12-28
[29] => 2011-12-29
[30] => 2011-12-30
[31] => 2011-12-31
)
)
my problem is i want to get 1 - 9 days like
2011-12-01, 2011-12-02 etc...
any idea how to get the output like that?
You could use sprintf.
sprintf('%1$02d', $i);
A different approach could be to use the DateTime object:
$aDates = array();
$oStart = new DateTime('2011-12-01');
$oEnd = clone $oStart;
$oEnd->add(new DateInterval("P1M"));
while($oStart->getTimestamp() < $oEnd->getTimestamp()) {
$aDates[] = $oStart->format('Y-m-d');
$oStart->add(new DateInterval("P1D"));
}
This should be sufficient. :)
$year = date('Y');
$month = date('m');
$dayCount = cal_days_in_month(CAL_GREGORIAN,$month,$year);
for ($i = 1; $i <= $dayCount; $i++)
{
$tree_data->data[$i] = $year."-".$month."-".str_pad($i, 2, "0", STR_PAD_LEFT);
}
$ret = implode(", ", $tree_data->data);
Check out str_pad().
http://php.net/manual/en/function.str-pad.php
$year = date('Y');
$month = date('m');
$dayCount = cal_days_in_month(CAL_GREGORIAN,$month,$year);
for ($i = 1; $i <= $dayCount; $i++)
{
$tree_data->data[$i] = $year."-".$month."-".(($i < 10)?'0'.$i:$i);
}
print "<pre>";
print_r($tree_data);
Well as other answers suggest you can add 0 to the day conditionally, or here is another way to go about the things just in case.
$startMonth = date('Y-m-01');
$endMonth = date('Y-m-t');
$i = 0;
while(strtotime($startMonth) <= strtotime($endMonth)){
$tree_date->date[$i] = $startMonth;
$startMonth = date('Y-m-d', strtotime($startMonth.' +1 days'));
$i++;
}
print_r($tree_date);

Categories