Display data in Arrray Horizontally - php

I've created and array and it works just how I wanted it to. The final part I wanted to attempt is to output the data horizontally but not sure how to.
<?php
$date = "2015-11-25";
$t = 0;
$startdate = "2009/06/01";
$start = strtotime($date);
$currentdate = $start;
$times_table = array();
for($i = 0; $i <= 3; $i++){
$times_table[$i] = array();
}
echo "<pre>";
for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 2; $j++){
if ($j == 0){
$times_table[$i][$j]= "Version 4" ;
}
else if ($j == 1){
$cur_date = date('Y/m/d', $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i][$j]= $cur_date ;
}
else{
$times_table[$i][$j]= "good" ;
}
}
}
print_r($times_table);
echo "</pre>";
?>

I'm not sure what you are trying to accomplish, but this looks like it should be in a table. For example:
<?php
$date = "2015-11-25";
$t = 0;
$startdate = "2009/06/01";
$start = strtotime($date);
$currentdate = $start;
$times_table = array();
for($i = 0; $i <= 3; $i++){
$times_table[$i] = array();
}
for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 2; $j++){
if ($j == 0){
$times_table[$i][$j]= "Version 4" ;
}
else if ($j == 1){
$cur_date = date('Y/m/d', $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i][$j]= $cur_date ;
}
else{
$times_table[$i][$j]= "good" ;
}
}
}
echo '<table>';
echo '<tr><th>Version #</th><th>Date</th><th>Status</th></tr>';
foreach($times_table as $times){
echo '<tr>';
foreach($times as $t){
echo '<td>',$t,'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
I should note that I would strongly discourage outputting raw data such as with print_r or var_dump for anything but debugging purposes that cannot find their way into the real world. It can be very bad for security.

Related

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.

Adding to months in array

Hi I've created an array where I increment "25/11/2015" by 1 month. I have a question about how it is working. I'm currently using "strtotime('+1 month', $currentdate)". I was wondering why in my first row of the array +1month isn't added straight away. Instead I am left with NOV-15 which is what I want but I was just wondering why this happens.
currently I'm getting:
Nov-15
Dec-15
Jan-16
why am i not outputting this result:
Dec-15
Jan-16
Feb-16
Heres my code:
$date = "2015-11-25";
$start = strtotime($date);
$currentdate = $start;
$times_table = array();
for($i = 0; $i <= 3; $i++){
$times_table[$i] = array();
}
echo "<pre>";
for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 4; $j++){
if ($j == 0){
$times_table[$i][$j]= "Version 5" ;
}
else if ($j == 1){
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i][$j]= $cur_date ;
echo $cur_date . ">". "<br />";
}
else{
$times_table[$i][$j]= "gary" ;
}
if ($j == 3) {
$numbers = mt_rand(1, 100);
$times_table[$i][$j]= $numbers ;
}
if ($j == 4){
if($i == 0 || $i == 3)
{
$pay = "P";
$times_table[$i][$j]= $pay ;
}
else{
$int = "I";
$times_table[$i][$j]= $int ;
}
}
}
}
What you write is what you get:
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i][$j]= $cur_date ;
You set the $currentdate value to $cur_date before one month was added, and then store the $cur_date value. This is the reason why it doesnt add 1 month straight away (it is added straight away to $currentdate but not to $cur_date)

Display dates in a HTML table for each month with PHP

I'm trying to display dates in a HTML table. I want to display each month, but I failed when the dates go over a month for example: 2015-30-11 to 2015-01-12
They break the table because there are too many <td>'s and I don't know how to display them in the next month.
Each user Has their own dates.
Code:
$month = date(m);
$year = date(Y);
$day = date(d);
if (isset($_GET['month'])) {
$month = $_GET['month'];
}
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo "<h2>$month-$day-$year</h2>";
echo "<h3>Amount of days: $days </h3>";
$days = $days + 1;
$employee_count = 0;
$sql = "SELECT * FROM employee WHERE inactive = 0";
$result = mysqli_query($con, $sql) or die ('Unable to execute query. ' . mysqli_error($con));
while ($row = mysqli_fetch_assoc($result)) {
$employee_id[] = $row;
$employee_count++;
}
echo "<table border='1'>";
echo "<tablehead>";
echo "<tr>";
for ($j = 0; $j < $days; $j++) {
echo "<th>$j</th>";
}
echo "</tr>";
echo "</tablehead>";
for ($i = 0; $i < $employee_count; $i++) {
echo "<tr>";
$id = $employee_id[$i]['employee_ID'];
$sql = "select * from employee where inactive = 0 and employee_ID = $id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$employee[] = $row;
}
$name = $employee[0]['name'];
$surname = $employee[0]['surname'];
echo "<td>$surname $name</td>";
$count_absences = 0;
$sql = "select * from absences where employee_FK = $id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$absences[] = $row;
$count_absences++;
}
$table = $days - 1;
$minus = 0;
for ($l = 0; $l < $table; $l++) {
for ($y = 0; $y < $count_absences; $y++) {
$start = $absences[$y]['start'];
$end = $absences[$y]['end'];
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$dDiff = $dStart->diff($dEnd);
$diff = $dDiff->days;
$diff = $diff + 1;
$date = $start;
$start_day = date('d', strtotime($date));
$start_day = $start_day - 1;
$start_month = date('m', strtotime($date));
$start_day = $start_day - 1;
if ($start_month == $month && $start_day == $l) {
for ($a = 0; $a < $diff; $a++) {
echo "<td>X</td>";
$l++;
}
}
}
echo "<td></td>";
unset($employee);
}
echo "</tr>";
unset($absences);
}
echo "</table>";
if ($month == 12) {
$next = 1;
} else {
$next = $month + 1;
}
if ($month == 1) {
$previous = 12;
} else {
$previous = $month - 1;
}
echo "<br>";
echo "<button type=\"button\" name=\"previous\" >Previous</button>";
echo "<button type=\"button\" name=\"next\" >Next</button>";
Revise your inner loop like this:
for($l=0;$l<$table;$l++){
$mark = false;
for($y=0; $y<$count_absences; $y++){
$start = $absences[$y]['start'];
$end = $absences[$y]['end'];
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$dDiff = $dStart->diff($dEnd);
$diff = $dDiff->days + 1;
$start_day = date('d', strtotime($start)) - 1;
$start_month = date('m', strtotime($start));
$lString = $year.'-'.$month.'-'.($l+1);
$lDate = new DateTime($lString);
if($lDate>=$dStart && $lDate<=$dEnd){
$mark = true;
break;
}
}
if($mark){
echo "<td>X</td>";
} else {
echo "<td></td>";
}
unset($employee);
}
That way on each iteration the specific day we're on for the employee will be checked against all date spans of their absence, even if absence spans across months.
I add this snippet:
if ($start_month != $month) {
echo '</tr><tr>';
}
It might be all you need, but I am not sure if that is going to work.
In any case you need to check if you are in a different month to switch to next line. I am not sure where that would be in your code.
<?
$month = date(m);
$year = date(Y);
$day = date(d);
if (isset($_GET['month'])) {
$month = $_GET['month'];
}
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo "<h2>$month-$day-$year</h2>";
echo "<h3>Amount of days: $days </h3>";
$days = $days + 1;
$employee_count = 0;
$sql = "SELECT * FROM employee WHERE inactive = 0";
$result = mysqli_query($con, $sql) or die ('Unable to execute query. ' . mysqli_error($con));
while ($row = mysqli_fetch_assoc($result)) {
$employee_id[] = $row;
$employee_count++;
}
echo "<table border='1'>";
echo "<tablehead>";
echo "<tr>";
for ($j = 0; $j < $days; $j++) {
echo "<th>$j</th>";
}
echo "</tr>";
echo "</tablehead>";
for ($i = 0; $i < $employee_count; $i++) {
echo "<tr>";
$id = $employee_id[$i]['employee_ID'];
$sql = "select * from employee where inactive = 0 and employee_ID = $id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$employee[] = $row;
}
$name = $employee[0]['name'];
$surname = $employee[0]['surname'];
echo "<td>$surname $name</td>";
$count_absences = 0;
$sql = "select * from absences where employee_FK = $id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$absences[] = $row;
$count_absences++;
}
$table = $days - 1;
$minus = 0;
for ($l = 0; $l < $table; $l++) {
for ($y = 0; $y < $count_absences; $y++) {
$start = $absences[$y]['start'];
$end = $absences[$y]['end'];
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$dDiff = $dStart->diff($dEnd);
$diff = $dDiff->days;
$diff = $diff + 1;
$date = $start;
$start_day = date('d', strtotime($date));
$start_day = $start_day - 1;
$start_month = date('m', strtotime($date));
$start_day = $start_day - 1;
if ($start_month != $month) {
echo '</tr><tr>';
}
if ($start_month == $month && $start_day == $l) {
for ($a = 0; $a < $diff; $a++) {
echo "<td>X</td>";
$l++;
}
}
}
echo "<td></td>";
unset($employee);
}
echo "</tr>";
unset($absences);
}
echo "</table>";
if ($month == 12) {
$next = 1;
} else {
$next = $month + 1;
}
if ($month == 1) {
$previous = 12;
} else {
$previous = $month - 1;
}
echo "<br>";
echo "<button type=\"button\" name=\"previous\" >Previous</button>";
echo "<button type=\"button\" name=\"next\" >Next</button>";
Maybe you should check in your loop that month of current date (in loop) is the same as month of previous date by keeping at the end of every loop the last value of month ($actualMonth). You probably have to setup this value outside the loop with null and ignore this verification if $actualMonth is null. Also, you can start verification after first loop.
If it's different, you have to break your loop. You can compare directly with your $month parameter.
OR
You could restrict your SQL query to get absence only for the month currently displayed.
MySQL :
SELECT * FROM employees WHERE MONTH(date_to_checked) = month_number;
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month

Looping through an array with PHP

I want to use PHP to populate an array starting with today's date and going several days into the future. When I tried the following below all of the columns contain "2013-11-18." I have been toying with it for 2 hours, but to no avail. What am I missing?
//Get "Day 0", today if undefined
if(isset($_GET['DAY0']) == TRUE){
$day0 = new DateTime($_GET['DAY0']);
} else {
$day0 = new DateTime('today');
}
// save day0 + 7 days into into dayArray
$dayArray[0] = $day0;
for($i=1; $i<8; $i++){
$day0->modify('+1 day');
$dayArray[i]= $day0;
}
echo "<tr>";
for ($i = 0; $i < 7; $i++) {
echo "<th>".$dayArray[i]->format('Y-m-d')."</th>";
}
echo "</tr>";
Objects are passed by reference. You are assigning multiple references to the same object in your array.
If you really need all the datetime objects in the array, you could do something like this
$interval = new DateInterval('P1D');
$start = new DateTime('today');
$dayArray = [clone $start];
for ($i = 1; $i < 8; $i++) {
$dayArray[] = clone $start->add($interval);
}
Or you could just store the formatted dates as already suggested.
$interval = new DateInterval('P1D');
$start = new DateTime('today');
$dayArray = [$start->format('Y-m-d')];
for ($i = 1; $i < 8; $i++) {
$dayArray[] = $start->add($interval)->format('Y-m-d');
}
Replace two of your $dayArray[i] with $dayArray[$i]
You could save timestamps:
// save day0 + 7 days into into dayArray
$dayArray[0] = $day0->format('U');
for($i=1; $i<8; $i++){
$day0->modify('+1 day');
$dayArray[$i] = $day0->format('U');
}
echo "<tr>";
for ($i = 0; $i < 7; $i++) {
echo "<th>".date('Y-m-d', $dayArray[$i])."</th>";
}
You can create a DatePeriod like so:
if(isset($_GET['DAY0']) == TRUE){
$day0 = new DateTime($_GET['DAY0']);
} else {
$day0 = new DateTime('today');
}
$enddate = new DateTime();
$period = new DatePeriod(
$day0,
new DateInterval('P1D'),
$enddate->add(new DateInterval('P7D'))
);
echo "<tr>";
foreach ($period as $datetime) {
echo "<th>".datetime->format('Y-m-d')."</th>";
}
echo "</tr>";

I want a PHP for loop that goes to certain number and again starts from zero

I want a PHP for loop that goes to certain number say "23" and again starts from "0".
Actually I want for the listing of time in 24 hours format and suppose a case is: I have to show time from 9 AM to 2 AM (i.e 9,10,11,12,13,14,...........23,0,1,2)
$i= range(0,23);//it doest work as it creates an array containing a range of elements
$start_time = 9;
$end_time = 2;
for ($i = $start_time ; $i<= $end_time ; $i++)
{
echo $i;
}
Please suggest a way.
Since your use-case mentions time-sensitive information you might be best off learning to use the date and strtotime functions (or the DateTime classes):
$time = strtotime('2013-09-14 02:00');
$endTime = strtotime('2013-09-15 09:00');
while ($time <= $endTime) {
echo date('Y-m-d H:i:s', $time)."\n";
$time = strtotime('+1 hour', $time);
}
// 2013-09-14 02:00:00
// 2013-09-14 03:00:00
// 2013-09-14 04:00:00
// 2013-09-14 05:00:00
// etc.
$start_time = 9;
$end_time = 2;
$end_time += ($end_time < $start_time) ? 24 : 0;
for ($i = $start_time; $i<= $end_time; $i++) {
echo ($i % 24);
}
Reason, the line $end_time += ($end_time < $start_time) ? 24 : 0; checks to see if the end time is less than the start time (which we assume means the next day), and if it is, it adds 24 hours to it. The line $i %24 is the modulus operator which will divide the number and give the remainder, so if it's 25, it will give you 1 back. Note that all hours being worked with will need to be in 24 hour format to use this method.
You can use the modulo to deduct 24 from numbers when they're greater than 23.
$start_time = 9;
$end_time = 2;
for( $i = $start_time; $i % 24 != $end_time; $i++ )
{
echo $i % 24;
}
Note that you need to be careful with this; if $end_time is greater than 23 it will be stuck in an infinite loop.
Try this its working
<?php
$i= range(0,23);//it doest work as it creates an array containing a range of elements
$start_time = 9;
$end_time = 2;
$max_value=23;
if($start_time>=$end_time)
{
for ($i = $start_time ; $i<= $max_value; $i++)
{
echo $i;
}
for($i=0; $i<=$end_time; $i++)
{
echo $i;
}
}
else
{
for ($i = $start_time ; $i<= $max_value; $i++)
{
echo $i;
}
}
?>
Again late to Answer , Try this
<?php
$start_time = 20;
$end_time = 10;
$maxTime=23;
$minTime=0;
for ($i = $minTime ; $i<=$maxTime - abs($start_time-$end_time) ; $i++)
{
$validTime= $start_time + ($i % $maxTime);
$validTime= $validTime>$maxTime?$validTime-$maxTime:$validTime;
echo $validTime;
}
?>
Check this out. Hope this helps
$start_time = 9;
$end_time = 2;
$flag = 1;
while($flag) [
echo $start_time . "<br>";
$start_time++;
if ($start_time == 23) { $start_time = 0; }
if ($start_time == $end_time) {
$flag = 0;
}
}
Does it have to be a for loop?
You can try this
function hours($range, $recurse = true, $end = array())
{
foreach($range as $time)
{
echo $time . "\n";
}
if($recurse && sizeof($end) > 0)
{
$range = range($end['start'], $end['end']);
hours($range, false);
}
}
$range = range(9,23);
$end = array('start' => 0, 'end' => 2);
hours($range, true, $end);
Maybe better to use date:
$hours = 8;
for ($i=1; $i<=8; $i++){
echo 'TIME1 = '.date("Y-m-d H:i:s",mktime (20+$i,15,18,06,05,2013)).'<br>';
}
or better DateTime class:
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2013-06-05 20:15:18');
$hours = 8;
for ($i=0; $i<8; $i++){
$date->add(new DateInterval('PT1H'));
echo 'TIME2 = '.$date->format('Y-m-d H:i:s').'<br>';
}
Thanks everybody for your help, using your ideas I got my work done.
Here is the code that actually worked.
$start_time = some_dynamic_value;
$end_time = some_dynamic_value;
$i= $start_time;
$flag = false;
if($start_time > $end_time)
$flag = true;
while ($i <= $end_time || $flag)
{
echo $i;
if($i == 24)
{
$i= 0;
$flag = false;
}
$i++;
}

Categories