Can not get my function to accept the PHP mysqli query array - php

I try to make a table where some cells shall have info according to an data base. If I do like this it works:
$date->modify('-1 day');
for ($x = 1; $x <=7; $x++) {
$date->modify('+1 day');
$b = true;
echo "<tr>", PHP_EOL;
echo "<td id='dag".$x."0' class='dag'>v".$date->format('W-D j/n')."</td>", PHP_EOL;
//*********** to function
foreach($t_tider as $field){
if ($field['datum'] == $date->format('Y-m-d') && $field['slot'] == 1){
echo "<td id='dag".$x."1'><div class='bokad'>".$field['lgh_nr']."-".$field['last_name']."</div></td>", PHP_EOL;
$b = false;
}
}
//***********
if($b) {
echo "<td id='dag".$x."1'>Ledig</td>", PHP_EOL;
}
// and so on, 7 rows and 5 columns and a header row
// but if I try to make a function of it it don’t recognize the array, only the first post are there.
function checkBokn($st, $tid, $d, $i){
foreach($st as $field){
if ($d->format('Y-m-d') == $field['datum'] && $field['slot'] == $tid){
echo "<td id='dag".$i.$tid."'><div class='bokad'>".$field['lgh_nr']."-".$field['last_name']."</div></td>", PHP_EOL;
return $bol = false;
}
// solved
/* else {
return $bol = true;
} */
}
return $bol = true; //moved
}
$b = checkBokn($t_tider, 2, $date, $x);
the $t_tider are an mysqli query.
BTW
Are there some way to add and subtract dates in strftime(), like on $date->modify('+1 day'); or make $date show days in another language than English?

Well I "solved" it, the else return breaks the loop, feeling stupid. Had to be after the loop.

Related

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

For loop variable, confused about single and double quotes

I'd like to make the following code a for loop to make everything read better, but I can't seem to get the quotes right and end up with a blank page
if ($_POST['week'])
{
$week = $_POST['week'];
}
//or check for a value submitted by the week menu
elseif ($_POST["user_week1"] == "week1") {
$week = "1";
}
elseif ($_POST["user_week2"] == "week2") {
$week = "2";
}
else if ($_POST["user_week3"] == "week3") {
$week = "3";
}
else if ($_POST["user_week4"] == "week4") {
$week = "4";
}
else if ($_POST["user_week5"] == "week5") {
$week = "5";
}
else if ($_POST["user_week6"] == "week6") {
$week = "6";
}
else {
$week = "1";
}
I tried to do:
if ($_POST['week'])
{
$week = $_POST['week'];
}
for ($i = 1; $i<7; $i++)
{
else if ($_POST["user_week'.$i.'"] == "week'.$i.'") {
$week = $i;
}
}
else {
$week = "1";
}
But that didn't work out too well, I tried using double quotes instead of single around the variables, plus '" and "' to no avail.
Can anyone help with this, or point me towards a good resource on single and double quotes for variables?
Are you all igrnoring the fact that the else if mustn`t be there!?
What you should do is the following
$week = "1";
if ($_POST['week']) {
$week = $_POST['week'];
} else {
for ($i = 1; $i < 7; $i++) {
if ($_POST["user_week" . $i] == "week" . $i) {
$week = $i;
break;
}
}
}
elseif ($_POST['user_week' . $i] == 'week' . $i)
above correction should work

Change variable inside function foreach loop

I've a problem that i can't solve. I think it's an easy fix, but after 3 hours of searching and trail-error. I've decided to ask the question over here:
This is my time function for a schedule application.
date_default_timezone_set('Europe/Amsterdam');
$current_time = time();
$unixtime = $current_time;
$time = date("Gi",$unixtime);
global $time;
function time_left($time, $active_class, $maxtime, $mintime){
if($time < $maxtime and $time > $mintime){
global $active_class;
$active_class = 'active';
echo 'succes!';
}
}
Here is my foreach loop, i loop through an array
foreach($rows as $row){
switch($hours){
case 1:
$t = '8:45 - 9:15';
$mintime = 845;
$maxtime = 914;
time_left($time, $maxtime, $mintime);
break;
case 2:
$t = '8:45 - 9:15';
$mintime = 845;
$maxtime = 914;
time_left($time, $maxtime, $mintime);
break;
/* etc.. etc.. etc... */
}
echo "<li class='" . $active_class ."'>";
echo "<div class='right'></div>";
echo "<div class='hour'>", $times, "</div><span class='divider-time'>|</span>";
$hours++;
$i = 0;
foreach($row[$day] as $r[1]){
$i++;
if ($i == 1) {
$class = 'vk';
} elseif ($i == 2) {
$class = 'lok';
} elseif ($i == 3) {
$class = 'doc';
}
echo "<span class='" . $class . "'>", $r[1], "</span>";
}
echo "</li>";
$class++;
}
I get the 'succes!' echo on the right location. But the active class is not working properly. The idea behind it is that the active class is only shown on one row. Now it searches for a match and everything behind it also gets the active class.
Thanks in advanced.
You should restart the $active_class variable in every iteration.
Otherwise, once it is set to active it won't change its value again.
foreach($rows as $row){
$active_class = '';
//YOUR CODE HERE
....
}

Creating a pagination function in PHP that exist in other class that generate the HTML

I need help creating a pagination function in PHP. I have created one that works great if it exist in the index page. I tried to put it in an PHP class it didn't work. Any help please. This is the code:
function paging($eu,$limit,$back,$next,$nume,$t1)
{
$l=1;
$i=0;
echo $eu; //$
echo $limit; // maximum record per page
//echo $back;
echo $next; //next page
echo $nume; // number of rows
if($back >=0)
{
$a = "<a _href='index?start=$back'>PREV</a>";
}
else
{
$a ="";
}
for($i=0;$i < $nume;$i=$i+$limit)
{
if($i <> $eu)
{
$b = " <='index?start=$i'>$l</a>";
$c = "";
}
else
{
$b = "";
$c =$l;
$l=$l+1;
}
}
if($t1 < $nume)
{
$e = "<='index.php?start=$next'>NEXT</a>";
}
$pg = "
<table>
<tr>
<td>$a</td>
<td>$b $c</td>
<td>$e</td>
</tr>
</table>
";
return $pg;
}
Most likely this is where you're messing up:
for($i=0;$i < $nume;$i=$i+$limit) {
if ($i <> $eu) {
$b = " <='index?start=$i'>$l</a>"; // <--- here
$c = "";
} else {
$b = ""; // <<--- here
$c =$l;
$l=$l+1;
}
}
You're overwriting the $b value on each loop iteration, instead of appending the "current" page HTML. Most likely you'd want something like this instead:
$b .= " <='index?start=$i'>$l</a>";
^--- concatenation operator
which is the same as doing:
$b = $b . " <='index?start=$i'>$l</a>";

how do I treat html in a loop when using MVC?

Can someone please show me how to do this basic thing using Zend Framework MVC?
I'm looping over the timestamp data and populating my table that way. i don't understand how I would pull my presentation HTML from this loop and stick it in the view? Any help would be greatly appreciated!
<table>
<?php
$day = date("j");
$month = date("m");
$year = date("Y");
$currentTimeStamp = strtotime("$year-$month-$day");
$numDays = date("t", $currentTimeStamp);
$counter = 0;
for($i = 1; $i < $numDays+1; $i++, $counter++)
{
$timeStamp = strtotime("$year-$month-$i");
if($i == 1)
{
// Workout when the first day of the month is
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay; $j++, $counter++)
echo "<td> </td>";
}
if($counter % 7 == 0) {
echo "</tr><tr>";
}
echo "<td>" .$i . "</td>";
}
?>
</table>
I'm wanting to turn the above code into functions, but the HTML is throwing me off.
******Edited**** (mvc solution added)
Don't clutter your code with unnecessary functions, partials, etc. Why bother with HTML from the start, when you can create your data, then transform it into an HTML table? Here's the MVC sample (the following code suppose a one module project called 'default', modify accordingly if the project is module based) :
[listing 1] application/controller/IndexController.php
class IndexController extends Zend_Controller_Action {
public function indexAction() {
$this->view->calData = new Default_Model_Calendar('2010-07-17');
}
}
[listing 2] application/models/Calendar.php
class Default_Model_Calendar {
/* #var Zend_Date */
private $_date;
/* #param Zend_Date|string|int $date */
public function __construct($date) {
$this->_date = new Zend_Date($date);
}
/* #return Zend_Date */
public function getTime() {
return $this->_date;
}
public function getData() {
// normally, fetch data from Db
// array( day_of_month => event_html, ... )
return array(
1 => 'First day of month',
4 => '<span class="holiday">Independence Day</span>',
17 => '<img src="path/to/image.png" />'
//...
);
}
}
[lisging 3] application/view/scripts/index/index.phtml
echo $this->calendarTable($this->calData);
[listing 4] application/view/helpers/CalendarTable.php
class Default_View_Helper_CalendarTable extends Zend_View_Helper_Abstract {
private $_calData;
public function calendarTable($calData = null) {
if (null != $calData) {
$this->_calData = $calData;
}
return $this;
}
public function toString() {
$curDate = $this->_calDate->getTime();
$firstDay = clone $curDate(); // clone a copy to modify it safely
$firstDay->set(Zend_Date::DAY, 1);
$firstWeekDay = $firstDay->get(Zend_Date::WEEKDAY);
$numDays = $curDate->get(Zend_Date::MONTH_DAYS);
// start with an array of empty items for the first $firstweekDay of the month
$cal = array_fill(0, $firstweekDay, ' ');
// fill the rest of the array with the day number of the month using some data if provided
$calData = $this->_calData->getData();
for ($i=1; $i<=$numDays; $i++) {
$dayHtml = '<span class="day-of-month">' . $i . '</span>';
if (isset($calData[$i])) {
$dayHtml .= $calData[$i];
}
$cal[] = $dayHtml;
}
// pad the array with empty items for the remaining days of the month
//$cal = array_pad($cal, count($cal) + (count($cal) % 7) - 1, ' ');
$cal = array_pad($cal, 42, ' '); // OR a calendar has 42 cells in total...
// split the array in chunks (weeks)
$calTable = array_chunk($cal, 7);
// for each chunks, replace them with a string of cells
foreach ($calTable as & $row) {
$row = implode('</td><td>', $row);
}
// finalize $cal to create actual rows...
$calTable = implode('</td></tr><tr><td>', $calTable);
return '<table class="calendar"><tr><td>' . $calTable . '</td></tr></table>';
}
public function __toString() {
return $this->__toString();
}
}
With this code, you can even set exactly what you want within the $cal array before calling array_chunk on it. For example, $cal[] = $dayHtml . 'more';
This also follow true MVC as data (in Default_Model_Calendar) and view (in Default_View_Helper_CalendarTable) are completely separated, giving you the freedom to use any other model with the view helper, or simply not using any view helper with your model!

Categories