do-while in php resulting a non-stop page loading - php

I want to have a $startdate counting 3 days backward from an input date by user, where those 3 days are not holidays.
So if the input date by user is October 22, the $startdate would be October 17 instead of October 19. Because October 19 and 20 are holidays
$i = 1;
do{
//some code to produce the $startdate
//...
//end
//check if $startdate is holiday or not
$this->db->where('hl_date',$startdate);
$query = $this->db->get('php_ms_holiday');
//if $startdate = holiday, it doesn't count
if($query->result_array()){
}
else{
$i++;
}
}while($i <= 3);
But, with that code I have a non-stop loading on the browser when a $startdate captured inside the if($query->result_array()) statement. And the browser can only returning results when I put something like this code below, inside the if($query->result_array()) statement:
$i = $i + n; //n is a number starting from 1, or
$i++;
but not:
$i = $i; //or
$i = $i + 0;
Why is that?

You just make a DB query which result interprets as TRUE. Maybe I wrong but it seems you are make the same db query in each loop iteration.
So, check your query, for example add specific date for holiday checking.

if($query->result_array()) will always evaluate to true, if your query is correctly formulated. So also if the number of rows returned is 0. This means that you never ever go to the else. You if-statement should check the number of results returned instead; Furthermore, I personally would prefer a normal for-loop:
for($i = 0; $i < 3)
{
//some code to produce the $startdate
//...
//end
//check if $startdate is holiday or not
$this->db->where('hl_date',$startdate);
$query = $this->db->get('php_ms_holiday');
//if $startdate = holiday, it doesn't count
if [num_rows equals 0] // test num_rows here; Not sure what your class offers here
{
$i++; // increment counter
// do whatever else you want to do
}
}

If this is always true:
if($query->result_array()){
}
Then this will always be true:
}while($i <= 3); //$i is never adjusted, so it will always be less than 3
Since you say that you want to display data from with the last 3 days but if there are holidays in between, you don't want to count them. To get around this I think you should not use the literal "3" since it can be adjusted, it should be a variable too.
A possible solution would be to have a variable such as:
$days_back = 3;
Then try to count the amount of holidays within the last 3 days(or something like that):
//You can make the holidays to be zero by default
$holidays = someWayToCountHolidays($startDate, $endDate); //You'll obviously have to code this
Then you can make make the variable your while loop will work agains
$num_days = $days_back + $holidays; //$holidays can be zero by default
Then something like below for you do while loop:
if($query->result_array()){
//Then do what ever you want to do here
} else {
//Then do what ever you want to do here
}
$i++; //Adjust $i
}while($i <= $num_days);

Related

PHP function - output of function is the input of another function

I have the following function where certain inputs are given and then 4 outputs are given: -
function rsiNext($dailyGainAvgPrev, $dailyLossAvgPrev,$cpDailyNext){
if($cpDailyNext > 0){
$dailyGainAvgNext = (($dailyGainAvgPrev * 13) + $cpDailyNext)/14;
}else{
$dailyGainAvgNext = (($dailyGainAvgPrev * 13) + 0)/14;
}
if($cpDailyNext < 0){
$dailyLossAvgNext = (($dailyLossAvgPrev*13) + abs($cpDailyNext))/14;
}else{
$dailyLossAvgNext = (($dailyLossAvgPrev*13) + abs(0))/14;
}
$relStrNext = $dailyGainAvgNext/$dailyLossAvgNext;
if($dailyLossAvgNext == 0){
$relStrIndNext = 100;
}else{
$relStrIndNext = 100-(100/(1+$relStrNext));
}
return array($dailyGainAvgNext, $dailyLossAvgNext, $relStrNext, $relStrIndNext);
}
I output the values using the following line of code:
//Get value for day 15
list($dailyGainAvg02, $dailyLossAvg02, $relStr02, $relStrInd02) = rsiNext($averageGains14, $averageLosses14, $priceDifferences[15]);
echo '<tr><td>'.$dailyGainAvg02.'</td><td>'.$dailyLossAvg02.'</td><td>'.$relStr02.'</td><td>'.$relStrInd02.'</td></tr>';
Now when I want the value for day 16 I use the following line of code:
//Get value for day 16
list($dailyGainAvg03, $dailyLossAvg03, $relStr03, $relStrInd03) = rsiNext($dailyGainAvg02, $dailyLossAvg02, $priceDifferences[16]);
echo '<tr><td>'.$dailyGainAvg03.'</td><td>'.$dailyLossAvg03.'</td><td>'.$relStr03.'</td><td>'.$relStrInd03.'</td></tr>';
The output of day 15 is the input of day 16, the output of day 16 is the input of day 17. The output of day 17 is the input of day 18, etc...
I need to repeat the list for 100 days. How can I go about it without repeating the list line for another 100 days?
Thank you.
Assuming you have the $priceDifferences array fully populated, something like the following should do:
$cur_dailyGainAvg = 0; // you need to initialize this value appropriately
$cur_dailyLossAvg = 0; // you need to initialize this value appropriately
for ($idx = 1; $idx <= 100; $idx++) {
list($new_dailyGainAvg, $new_dailyLossAvg, $new_relStr, $new_relStrInd) = rsiNext($cur_dailyGainAvg, $cur_dailyLossAvg, $priceDifferences[$idx])
// print
echo '<tr><td>'.$new_dailyGainAvg.'</td><td>'.$new_dailyLossAvg.'</td><td>'.$new_relStr.'</td><td>'.$new_relStrInd.'</td></tr>';
// shift the new values onto the current, and repeat the calculation
$cur_dailyGainAvg = $new_dailyGainAvg;
$cur_dailyLossAvg = $new_dailyLossAvg;
}
Basically distinguish between your "current" values, which you feed into your function, and the "new" values that come out, then "shift" the new onto the current ones and repeat.
You may have to check the boundaries of the loop.

calendar with sql

PHP+SQL question:
I have table for assignments
one of the field is "progTargetDate" -> linux time (eg: 1348185600 )
I also built calender and I want to check if I have any assignment for each day I print
so - I wrote the query that bring me all the assignment for the current month
$query = mysql_query("SELECT ass.id, ass.title, ass.des, ass.progTargetDate
FROM pro_assignments AS ass, pro_progs2assignments AS pr
WHERE (ass.progTargetDate >= $ChoosenMonth_start) AND
(ass.progTargetDate <= $ChoosenMonth_end)
ORDER BY ass.progTargetDate ASC
");
(I delete part of the SQL query))
and I have the loop that build the calendar cell
for ($i = 1 ; $i <= $total_days_in_month ; $i++)
{
}
$i = each day in the month
I tried to build IF condition without success
I want to check for each day if it found inside the array (that I got from the first query)
(this code goes inside the FOR loop:)
echo "<td>$i";
while($index = mysql_fetch_array($query))
{
$progTargetDate = $index['progTargetDate'];
if ((mktime(0, 0, 0, date($ChoosenMonth) , $i, date($ChoosenYear)) == $progTargetDate))
echo "<p>found</p>";
else
echo "<p>not</p>";
}
echo "</td>";
What do I do wrong?
for 31 days I should have 31 cell with "found" or "not" in each one. but for some reason only in the first cell I see this result

using do..while ,continue?

<?php
// initial value
$week = 50;
$year = 2001;
$store = array();
do
{
$week++;
$result = "$week/$year";
array_push($store,$result);
if($week == 53){
$week = 0;
$year++;//increment year by 1
}
continue;
}
// End of Loop
while ($result !== "2/2002");
?>
print_r($store);
result want return will be
array("51/2001", "52/2001", "01/2002", "02/2002");
What is my problems by using while using do..while ,continue?
Your arguments to array_push are the wrong way around. Read the manual entry for functions you use. Turn on warnings on your server; running this in codepad showed me the problem immediately. [Edit: You have now quietly fixed that in your question.]
You also have a typo: $i instead of $week.
Finally, you test against "02/2002", but for that month the string will be "2/2002".
Fixed code (live demo):
<?php
// initial value
$week = 50;
$year = 2001;
$store = array();
do
{
$week++;
$result = "$week/$year";
array_push($store, $result);
if($week == 53){
$week = 0;
$year++;//increment year by 1
}
continue;
}
// End of Loop
while ($result !== "2/2002");
?>
In general, I'd recommend against loops like this. As you've discovered, your code is very fragile because you're testing for just one very specific value, and if that value is not precisely correct you get an infinite loop.
Instead, consider comparing $week and $year separately and numerically:
while ($week < 2 && $year <= 2002)
Next time please include in your question the output that you are seeing, as well as the output that you want to see. It'll save us time in reproducing your problem.
I may not be understanding this correctly... If you could explain a bit more that'd help.
Try turning the loop into a function, and turn the while(..) to check the functions variable.
then just call it 4 times to fill your array.

Adding rows to an array in PHP

I have loaded an associative array of records from a MySQL database table.
The array consists of 1 to 7 rows representing one week of entries,
which might not have been entered for each day.
How can I insert blank rows into the array for the missing days
so that I can easily display the data in a table?
I don't need to update the database with the blanks.
Example:
Field1 Field2 Field3 Field4 .... Field#
Record[0]
Record[1]
Record[2]
Record[3]
Record[4]
Record[5]
Record[6]
Field4 is the date as yyyy-mm-dd
I load the array automatically using a start date and end date
Some weeks there will be a Sun, Tue, and Fri or Mon, Tue, Wed, Fri & Sat.
this is simple:
Do you know how many "Fields" you have for each day? let's say it's "num of fields"
$records = array_fill(0, 7, array_fill(0, <num of fields>, ''));
what this does is it creates a blank array from [0] to [6] and for each array element it inserts another array of "Fields", with "num of fields", each of which is set to an empty string ''.
Now that you have this, you read your data from the mysql table and if you selectively assign $records by index (i'm assuming), the rest of them will stay blank.
Keep in mind that you can reassign an element of $records array by using something like
$records[5] = array('New value', 'Field2 value');
which is what you do when you read data from mysql table.
Do you use some kind of index in your mysql table to correspond to the numbered day in a week?
comment here if you get stuck with mysql part.
If your array is associative, then when constructing the table why not just check for and skip the empty rows? As an example:
Example 1:
if ($row['Monday'] == '')
{
// draw blank template
}
else
{
// draw using live data
}
Based on added example (untested; for php 5.1 and above):
Example 2:
for($i = 0; $i < count($Record); $i++)
{
$recordDate = strtotime($Record[$i][field4]);
$dayOfWeek = $date('N', $recordDate);
switch ($dayOfWeek)
{
case '1':
// Monday
break;
case '2':
// Tuesday
break;
// and so on...
}
}
Edit
The above code assumed that your rows are in weekday order, with possible omissions. The problem with the first example, is that the array is not associative quite like the example. The problem with the second example, is that a missing weekday row results in a completely skipped output, which could provide a table like MTWFS (skipped Thursday).
So, you need to build a loop that draws each day of the week, and checks all of the rows for the appropriate day to draw. If the day is not found, an empty day is drawn:
Example 3:
$dayNames = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'};
// Loop that walks the days of the week:
for($d = 1; $d < 7; $d++)
{
// Loop that checks each record for the matching day of week:
$dayFound = false;
for($i = 0; $i < count($Record); $i++)
{
$recordDate = strtotime($Record[$i][field4]);
$dayOfWeek = $date('N', $recordDate);
// output this day name in your own formatting, table, etc.
echo $dayNames[$i];
if ($dayOfWeek == $d)
{
// output this day's data
$dayFound = true;
break;
}
if (!$dayFound)
{
// output a blank template
}
}
}
Edit 2
Ok it seems you are more interested in having a fully populated array of weekdays than an output routine (I was assuming you would just want to draw the tables in php or something). So this is my example of how to arrive at a 7-day array with no gaps:
Example 4:
$weekData = array(); // create a new array to hold the final result
// Loop that walks the days of the week, note 0-based index
for($d = 0; $d < 6; $d++)
{
// Loop that checks each record for the matching day of week:
$dayFound = false;
for($i = 0; $i < count($Record); $i++)
{
$recordDate = strtotime($Record[$i][field4]);
$dayOfWeek = $date('N', $recordDate);
// Add one to $d because $date('N',...) is a 1-based index, Mon - Sun
if ($dayOfWeek == $d + 1)
{
// Assign whatever fields you need to the new array at this index
$weekData[$d][field1] = $Record[$i][field1];
$weekData[$d][field2] = $Record[$i][field2];
$weekData[$d][field3] = $Record[$i][field3];
$weekData[$d][field4] = $Record[$i][field4];
// ...
break;
}
if (!$dayFound)
{
// Assign whatever default values you need to the new array at this index
$weekData[$d][field1] = "Field 1 Default";
// ...
}
}
}
Without having seen your current code (as requested in the comments by Felix Kling), my guess is that you will need to loop through your array, passing it to a function (or passing the array to the function) which checks Field4 and keeps track of which days of that week have data and fills in those missing days. This would be easier if the array was in order to start with (as you would only need to track the previous 'entry' rather than the entire week).
I'm a bit busy currently, here's some pseduo-code that will need to be expanded etc.
$formattedWeek = getFormattedWeek($inputArray);
function getFormattedWeek($input) {
$nextDay = 'Sunday';
foreach ($input as $entry) {
if (date-call-that-returns-day-of-the-week !== $nextDay) {
$output[] = 'add whatever you need to your array';
} else {
$output[] = $entry;
}
$nextDay = call-to-increase-the-day-or-loop-back-to-Sunday();
}
return $output;
}
You should get the picture.

Calculate greatest number of days between two consecutive dates

If you have an array of ISO dates, how would you calculate the most days between two sequential dates from the array?
$array = array('2009-03-11', '2009-03-12', '2009-04-12', '2009-05-03', '2009-10-30');
I think I need a loop, some sort of iterating variable and a sort. I can't quite figure it out.
This is actually being output from MYSQL.
Here is how you can do it in PHP:
<?php
$array = array('2009-03-11', '2009-03-12', '2009-04-12', '2009-05-03', '2009-10-30');
# PHP was throwing errors until I set this
# it may be unnecessary depending on where you
# are using your code:
date_default_timezone_set("GMT");
$max = 0;
if( count($array) > 1 ){
for($i = 0; $i < count($array) - 1; $i++){
$start = strtotime( $array[$i] );
$end = strtotime( $array[$i + 1] );
$diff = $end - $start;
if($diff > $max) $max = $diff;
}
}
$max = $max / (60*60*24);
?>
It loops throw your items (it executes one less time than there are number of items) and compares each one. If the comparison is larger than the next, it updates max. Time is in seconds, so after the loop is over we convert the seconds into days.
This PHP script will give you the largest interval
1 ){
for($i = 0; $i $maxinterval) $maxinterval = $days;
}
}
?>
EDIT:
As [originally] worded the question can be understood in [at least ;-)] two ways:
A) The array contains a list of dates in ascending order. The task is to find the longuest period (expressed in number of days) between to consecutive dates in the array.
B) The array is not necessarily sorted. The task is to find the longuest period (expr. in number of days) between any two dates in the array
The following provides an answer to the "B" understanding of the question. For a response to "A", see dcneiner's solution
No Sorting needed!...
If it comes from MySQL, you may have this DBMS returns directly the MIN and MAX values for the considered list.
EDIT: As indicated by Darkerstar, the way the way the data is structured [and also the existing SQL query which returns the complete list as indicated in the question] generally dictate the way the query which produces the MIN and MAX value should be structured.
Maybe something like this:
SELECT MIN(the_date_field), MAX(the_date_field)
FROM the_table
WHERE -- whatever where conditions if any
--Note: no GROUP BY needed
If, somehow, you cannot use SQL, a single pass through the list will allow you to obtain the MIN and MAX value in the list (in O(n) time, that is).
Algorithm is trivial:
Set Min and Max Value to first item in [unsorted] list.
Iterate through each following item in the list, comparing it with the Min Value and replacing it if found smaller, and doing like-wise for the Max value...
With Min and Max values in hand, a simple difference gives the max number of days...
In PHP, it's looks like the following:
<?php
$array = array('2009-03-11', '2009-03-12', '2009-04-12', '2009-05-03', '2009-10-30');
# may need this as suggested by dcneiner
date_default_timezone_set("GMT");
$max = $array[0];
$min = $max;
for($i = 1; $i < count($array); $i++){
// Note that since the strings in the array are in the format YYYY-MM-DD,
// they can be compared as-is without requiring say strtotime conversion.
if ($array[$i] < $min)
$min = $array[$i];
if ($array[$i] > $max)
$max = $array[$i];
}
$day_count = (strtotime($max) - strtotime($min)) / (60*60*24);
?>

Categories