How to get data column separated in foreach loop - php

How to get data in different section like today, upcoming, and overdue date with the help of foreach loop.
foreach($list as $index=>$row) {
$dueDt = new DateTime($row->due_timeDate);
$todayDt = new DateTime('now');
$due = $dueDt->format('Y-m-d');
$today = $todayDt->format('Y-m-d');
if($due == $today) {
echo $due.' Today' ;
echo '<br>';
$task['today'][]=$row;
} elseif($due>$today) {
echo $due.' Upcoming';
echo '<br>';
$task['today'][]=$row;
} elseif($due<$today) {
echo $due.' Overdue';;
echo '<br>';
$task['overdue'][]=$row;
}
}
My data is coming like this:
2015-10-30 Upcoming
2015-10-29 Today
2015-10-28 Overdue
2015-10-28 Overdue
2015-10-27 Overdue
2015-10-27 Overdue
2015-10-15 Overdue
But I want the data like this from foreach loop:
Upcoming
2015-10-30
Today
2015-10-29
Overdue
2015-10-28
2015-10-28
2015-10-27
2015-10-27
2015-10-15

$task['today'] = array();
$task['Upcoming'] = array();
$task['Overdue'] = array();
foreach ($list as $index => $row)
{
$dueDt = new DateTime($row->due_timeDate);
$todayDt = new DateTime('now');
$due = $dueDt->format('Y-m-d');
$today = $todayDt->format('Y-m-d');
if ($due == $today)
{
$task['today'][] = $row;
}
elseif ($due > $today)
{
$task['Upcoming'][] = $row;
}
elseif ($due < $today)
{
$task['Overdue'][] = $row;
}
}
foreach ($tasks as $dueDate => $task)
{
if (!empty($task))
{
echo $dueDate . "<br />";
foreach ($task as $date)
{
echo " " . $date . "<br />";
}
}
}

You need to use key value pairs of your array.
Take key as time (Today, Tomorrow, Overdue).
This should be a multi-dimensional array.
Print in loop like following:
<?php
$tasks = array();
foreach($list as $index=>$row) {
$dueDt = new DateTime($row->due_timeDate);
$todayDt = new DateTime('now');
$due=$dueDt->format('Y-m-d');
$today=$todayDt->format('Y-m-d');
if($due==$today) {
$tasks['today'][] = $due;
}
else if($due>$today) {
$tasks['upcoming'][]=$due;
}
else if($due<$today) {
$tasks['overdue'][]=$due;
}
}
if (! empty($tasks)) {
foreach ($tasks as $dueDate => $task) {
echo ucwords($dueDate);
if (! empty($task)) {
foreach ($task as $title) {
echo "<br/>--> " . $title;;
}
}
}
}
?>

Try this
foreach($list as $index=>$row) {
$dueDt = new DateTime($row->due_timeDate);
$todayDt = new DateTime('now');
$due=$dueDt->format('Y-m-d');
$today=$todayDt->format('Y-m-d');
if($due==$today){
$up['upcome']=$row;
}elseif($due>$today){
$to['Today']=$row;
}elseif($due<$today){
$over['overdue']=$row;
}
if (!empty($up)) {
echo "Upcoming";
foreach ($up as $new_up) {
echo " " . $new_up['upcome']."<br>";
}
}
if (!empty($to)) {
echo "Today";
foreach ($to as $new_to) {
echo " " . $new_to['Today']."<br>";
}
}
if (!empty($over)) {
echo "Overdue";
foreach ($over as $new_over) {
echo " " . $new_over['overdue']."<br>";
}
}
}
Output will be
Upcoming
2015-10-30
Today
2015-10-29
Overdue
2015-10-28
2015-10-28
2015-10-27
2015-10-27
2015-10-15

According to your data-structure:
$data = ['2015-10-25','2015-10-26','2015-10-27','2015-10-28','2015-10-29','2015-10-30'];
$current = '2015-10-27';
// Saving Array Keys for future work
$rows = array('overdue','today','upcomming');
foreach($data as $date) {
// Compare each date to find our $rows array
$curt = strtotime($current);
$d = strtotime($date);
if($d < $curt) {
$rows['overdue'][] = $date;
} else if($d > $curt) {
$rows['upcomming'][] = $date;
} else if($d == $curt) {
$rows['today'][] = $date;
}
}
//Now Print each $rows:
echo 'Overdue: <br>'. implode('<br>', $rows['overdue']) .'<br><br>';
echo 'Today: <br>'. implode('<br>', $rows['today']) .'<br><br>';
echo 'Upcomming: <br>'. implode('<br>', $rows['upcomming']);
Prints:
Overdue:
2015-10-25
2015-10-26
Today:
2015-10-27
Upcomming:
2015-10-28
2015-10-29
2015-10-30

Related

Array: Each User has only one row

I am trying to test an Calendar-System.
The events get loaded successfully, but get displayed in different rows.
How can I just create only one row per user (id) and add the data to that specific row?
Code:
foreach($stuArr as $student) {
$id = $student[0];
$dates = $student[1];
$name = $student[2];
$time = $student[3];
$state = $student[4];
echo "<tr>";
echo "<td>".$id."</td>";
echo "<td>".$name."</td>";
for ($j = 1; $j <= $days_in_month; $j++) {
if(in_array($j, $dates))
echo "<td>".$time."".$state."</t>";
else
echo "<td> </td>";
}
echo "</tr>";
}
If you need more Code, just say it. I am PHP beginner and dont know which Code you need. But this is the part, where the row is generated.
Edit:
foreach($data as $student) {
$id = $student->id;
$name = $student->name;
$mark = false;
foreach($data2 as $cal) {
if($cal->resource == $id) {
$start = new DateTime(substr($cal->start, 0, 10));
$end = new DateTime(substr($cal->end, 0, 10));
//$interval = DateInterval::createFromDateString('1 day');
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval ,$end);
$time = $cal->time;
$state = $cal->state;
$dd = [];
if($month == $start->format('n')) {
foreach ($period as $dt) {
if($month != $dt->format('n'))
break;
$dd[] = $dt->format("j");
}
$stuArr[] = [$id, $dd, $name, $time, $state];
}
}
}
}
Make $stuArr an associative array that uses the student ID as the key.
Then nest each scheduled item as a nested array in this, and add another loop to find all the items on each date.
I've also changed the code to use associative arrays for the rows, rather than having magic number indexes.
<?php
foreach ($data as $student) {
$id = $student->id;
$name = $student->name;
$items = [];
foreach ($data2 as $cal) {
if ($cal->resource == $id) {
$start = new DateTime(substr($cal->start, 0, 10));
if ($month != $start->format('n')) {
continue;
}
$end = new DateTime(substr($cal->end, 0, 10));
//$interval = DateInterval::createFromDateString('1 day');
$end = $end->modify('+1 day');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
$time = $cal->time;
$state = $cal->state;
$dd = [];
foreach ($period as $dt) {
if ($month != $dt->format('n'))
break;
$dd[] = $dt->format("j");
}
$items[] = ['days' => $dd, 'time' => $time, 'state' => $state];
}
}
$stuArr[$id] = ['name' => $name, 'items' => $items];
}
foreach ($stuArr as $id => $student) {
$name = $student['name'];
echo "<tr>";
echo "<td>" . $id . "</td>";
echo "<td>" . $name . "</td>";
for ($j = 1; $j <= $days_in_month; $j++) {
$date_item = "";
foreach ($student['items'] as $item) {
if (in_array($j, $item['days'])) {
$date_item .= "{$item['time']}{$item['state']}";
break;
}
}
if ($date_item) {
echo "<td>$date_item</td>";
} else {
echo "<td> </td>";
}
}
echo "</tr>";
}
If you use the id as the index then you can have one row with multiple dates. Instead of this:
$stuArr[] = [$id, $dd, $name, $time, $state];
Do something like this to append the dates:
if(!isset($stuArr[$id])) {
$stuArr[$id] = ['dates' => $dd, 'name' => $name, 'time' => $time, 'state' => $state];
} else {
$stuArr[$id]['dates'] = array_merge($stuArr[$id]['dates'], $dd);
}
Then to display just use the new indexes:
foreach($stuArr as $key => $student) {
$id = $student[$key];
$dates = $student['dates'];
$name = $student['name'];
$time = $student['time'];
$state = $student['state'];
//etc...
FYI, you haven't closed the </td> correctly in this code:
echo "<td>".$time."".$state."</t>";

mysqli query inside a while and foreach

Here's my code:
while($listAll = $listAllHere->fetch_assoc()) {
$whos = array();
$j_out = array();
$whos[] = $listAll['user_id'];
$j_out[] = $listAll['j_out'];
foreach ($j_out as $time) {
$timeleft = $time - $now;
if ($timeleft >= 0) {
foreach ($whos as $ids) {
echo "<div class=\"col-xs-3\"><a href=\"#\" class=\"btn btn-default\"><b>".$ids."</b><br />";
echo "<div class=\"badge\">".$timeleft."s</div></a></div>";
}
} else {
foreach ($whos as $ids) {
$noone[] = $ids + 1;
}
}
}
}
How can I query other table using each $ids to get username and display them?

How to add a count == 0 to this?

I would like to add a count == 0 which if it is the case, just outputs 'please contact us to find out the dates', but I can't seem to get it to work. Please can someone advise?
$count = 0;
$your_repeater = get_field('add_date');
if ($your_repeater) {
while (have_rows('add_date')):
the_row();
$count++;
$my_field = get_sub_field('course_date');
if ($count == 0) {
echo 'please contact us to find out dates';
} else {
echo '';
}
if ($count == 1) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
// echo $my_field .', ';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>1. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo 'Contact us to find out more';
} else {
echo '';
}
}
if ($count == 2) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>2. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo '<img src="' .bloginfo('url').'/wp-content/themes/derbyskillbuild site/images/hourglass.png" />';
} else {
echo '';
}
}
if ($count == 3) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b> 3. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
} else {
echo '';
}
}
if ($count == 4) {
}
if ($count == 5) {
}
echo '</ul>';
endwhile;
}
It appears that you are checking the count way too soon in your code.
You start with a $count = 0;, but then in the while loop you first do $count++. So, at this point, the count is 1. Then a few lines later you check this:
if ($count == 0) {
echo 'please contact us to find out dates';
}
This will never return true, since you just did a $count++ from 0, so at this point it's always at least 1. It seems that this check should be outside of your while loop and you're currently closing the loop way too late.

How to move page to the required path?

I make a php page in which i get data from bar but when i click cmd=7 and mode=test it moves cmd=default,how i set the links to the desired pages.
Here is my code:
function default1(){
$mode=$_GET['mode'];
if($mode=='')
{
$mode=$_POST['mode'];
}
$dates = array();
$timestamp = strtotime('-30 days');
for ($i = 0 ; $i <=30 ; $i++) {
//insert the date
$dates[$i]= date('m-d-Y', $timestamp);
//increase the day
$timestamp += 24 * 3600;
}
//print_r ($dates);
$strQuery="select DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y') as transaction_date,sum(amount)as Amount from transactions where mode='".$mode."' group by DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y')";
$result = $GLOBALS ['mysqli']->query ($strQuery) or die ($GLOBALS ['mysqli']->error . __LINE__);
while($rs=$result->fetch_assoc ())
{
$res[]=$rs;
}
//print_r ($res);
$strXML = "<chart caption='Reports of transactions' xAxisName='Date' yAxisName='Amount' showValues='0' useRoundEdges='1' palette='3'>";
for ($i = 0 ; $i <=30 ; $i++) {
foreach($res as $r)
{
if($r['transaction_date']==$dates[$i]){
$str = $r['transaction_date'];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='" .$r['Amount']."' />";
break;
}
else {
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
}
$strXML .=$substrXML;
}
$strXML .= "</chart>";
return $strXML;
}
function past7days(){
//$mode=$_GET['mode'];
//if($mode=='')
//{
//$mode=$_POST['mode'];
//}
$dates = array();
$timestamp = strtotime('-7 days');
for ($i = 0 ; $i <=7 ; $i++) {
$dates[$i]= date('m-d-Y', $timestamp);
$timestamp += 24 * 3600;
}
$strQuery="select DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y') as transaction_date,sum(amount)as Amount from transactions WHERE transaction_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() and mode='".$mode."' group by DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y')
";
$result = $GLOBALS ['mysqli']->query ($strQuery) or die ($GLOBALS ['mysqli']->error . __LINE__);
while($rs = $result->fetch_assoc ())
{
$res[]=$rs;
}
$strXML = "<chart caption='Reports of transactions' xAxisName='Date' yAxisName='Amount' showValues='0' useRoundEdges='1' palette='3'>";
for ($i = 0 ; $i <=7 ; $i++) {
if(mysqli_num_rows($result)>0){
foreach($res as $r)
{
if($r['transaction_date']==$dates[$i]){
$str = $r['transaction_date'];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML.="<set label='".$transactiondate."' value='".$r['Amount']."' />";
break;
}
else {
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
}
}
else{
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
$strXML .=$substrXML;
}
$strXML .= "</chart>";
return $strXML;
}
if($_GET['cmd']=='' || $_GET['cmd']=='default' )
{
?>
<? echo date('M jS Y' ,strtotime($startdate)); ?> to <? echo date('M jS Y' ,strtotime($enddate)); ?>
<?
}
else
{
?>
<? echo date('M jS Y' ,strtotime($startdate)); ?> to <? echo date('M jS Y' ,strtotime($enddate)); ?>
<?
}
if($_GET['cmd']=='7')
{
?>
<span style="margin-left:10px;">Past 7 Days</span>
<?
}
else
{
?>
Past 7 Days
<?
try it
if($_GET['cmd']=='' || $_GET['cmd']=='default' )
{
echo date('M jS Y' ,strtotime($startdate))." To ".date('M jS Y' ,strtotime($enddate));
}
else
{
$url = "merchant/products/1/manage/reports?cmd=default&mode=".$_GET['mode'];
header("location:".$url);
exit;
}
if($_GET['cmd']=='7')
{
echo '<span style="margin-left:10px;">Past 7 Days</span>';
}
else
{
$url = "merchant/products/1/manage/reports?cmd=7&mode=".$_GET['mode'];
header("location:".$url);
exit;
}
<script type="text/javascript">
document.location.href = '/merchant/products/1/manage/reports?cmd=7&mode=<?php echo $_GET["mode"]; ?>';
</script>

retrieve data based on date range using mysql ,php

I am working on WPF where I have two datepickers when I try to retrieve the information on date range it displays only one record on all dates(same record displaying multiple times eg : date chosen from 01/10/2013 - 3/10/2013) where I have 3 different records on each day but my output is the first record displayed 3 times with same date and time.
function cpWhitelistStats() {
$startDate = $_POST['startDate'];
$startDateTime = "$startDate 00:00:00";
$endDate = $_POST['endDate'];
$endDateTime = "$endDate 23:59:59";
$cpId = $_POST['id'];
$cpName = etCommonCpNameById($cpId);
print "<h2 style=\"text-align: center;\">Permitted Vehicle Summary</h2>";
print "<h2 style=\"text-align: center;\">for $cpName</h2>";
$tmpDate = explode("/", $startDate);
$startYear = $tmpDate[2];
$startMonth= $tmpDate[1];
$startDay = $tmpDate[0];
$tmpDate = explode("/", $endDate);
$endYear = $tmpDate[2];
$endMonth= $tmpDate[1];
$endDay = $tmpDate[0];
$startDateTime = "$startYear-$startMonth-$startDay 00:00:00";
$endDateTime = "$endYear-$endMonth-$endDay 23:59:59";
$custId = $_SESSION['customerID'];
$realCustomerId = $_SESSION['realCustomerId'];
$maxVal = 0;
if ($custId != "") {
$conn = &newEtConn($custId);
// Get the whitelist plates
$staticWhitelistArray = etCommonMkWhitelist($conn, $cpId);
array_shift($staticWhitelistArray);
$startLoopDate = strtotime($startDateTime);
$endLoopDate = strtotime($endDateTime);
$oneDay = 60 * 60 * 24;
// Get the entries
$plateList = array_keys($staticWhitelistArray);
$plate_lookup = implode('","', $plateList);
$sql = "SELECT plate, entry_datetime, exit_datetime FROM stats WHERE plate IN (\"$plate_lookup\") AND entry_datetime > \"$startDateTime\" AND entry_datetime < \"$endDateTime\" AND carpark_id=\"$cpId\" ";
$result = $conn->Execute($sql);
if (!$result) {
print $conn->ErrorMsg();
exit;
}
$rows = $result->fields;
if ($rows != "") {
unset($myArray);
foreach($result as $values) {
$plate = $values['plate'];
$new_platelist[] = $plate;
$inDateTime = $values['entry_datetime'];
$outDateTime = $values['exit_datetime'];
$tmp = explode(' ', $inDateTime);
$inDate = $tmp[0];
$in_ts = strtotime($inDateTime);
$out_ts = strtotime($outDateTime);
$duration = $out_ts - $in_ts;
$dur_array = intToDateArray($duration);
$dur_string = '';
if ($dur_array['days'] > 0) {
$dur_string .= $dur_array['days'] . ' days ';
}
if ($dur_array['hours'] > 0) {
$dur_string .= $dur_array['hours'] . ' hours ';
}
if ($dur_array['mins'] > 0) {
$dur_string .= $dur_array['mins'] . ' minutes ';
}
if ($dur_array['secs'] > 0) {
$dur_string .= $dur_array['secs'] . ' secs ';
}
$myArray[$plate][] = array($inDateTime, $outDateTime, $inDate, $dur_string);
}
}
while ($startLoopDate < $endLoopDate) {
$dayString = strftime("%a, %d %B %Y", $startLoopDate);
$dayCheck = strftime("%Y-%m-%d", $startLoopDate);
print "<h2>$dayString</h2>";
print "<table width=\"100%\">";
print " <tr>";
print " <th>VRM</th>";
print " <th>Permit Group</th>";
print " <th>Entry Time</th>";
print " <th>Exit Time</th>";
print " <th>Duration</th>";
print " </tr>";
foreach($new_platelist as $wlPlate) {
if ($myArray[$wlPlate][0][2] == $dayCheck) {
print "<tr>";
print "<td>$wlPlate</td>";
if (isset($myArray[$wlPlate])) {
print "<td>".$staticWhitelistArray[$wlPlate]['groupname']."</td>";
print "<td>".$myArray[$wlPlate][0][0]."</td>";
print "<td>".$myArray[$wlPlate][0][1]."</td>";
print "<td>".$myArray[$wlPlate][0][3]."</td>";
}
else {
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
}
print "</tr>";
}
}
print "</table>";
$startLoopDate = $startLoopDate + $oneDay;
}
}
}
Can you echo this query so we can see what's actually being sent...
$sql = "
SELECT plate
, entry_datetime
, exit_datetime
FROM stats
WHERE plate IN ('$plate_lookup')
AND entry_datetime BETWEEN '$startDateTime' AND '$endDateTime'
AND carpark_id= '$cpId';
";
(This isn't an answer, but I wanted to make use of the additional formatting options)

Categories