Dynamic X-axis graph that will change according to the count of rows - php

Let's say I have a mysql table with an id, some measurements and a DATE column.
Example: id, measurements, date_entered
This table stores some measurements of a patient so as to keep a record for him.
I want to make a graph which according to the count of rows that exist in the database will change dynamically the X-axis.
For example, if there are only 7 rows in the table I need to represent 7 days to the graph with the measurement for every day. If there are more than 14 days, I want it to change to respresent 2 weeks on X-axis and the average measurements(average for 1 week and average for the other too) on Y-axis and so on from weeks to months.
Can anyone help me on this? I cannot think of something that will do in my case..
I use JPGraph to make the line graph but i don't have a problem there. My problem is on how to handle the results.
I hope you will understand what I need! Thanks.

Something like this?
// Get the results from the database
$query = "SELECT `data_col` FROM `table` WHERE `condition_col` = 'some value'";
$result = mysql_query($query);
// Get all results into array and count them
$results = array();
for ($i = 0; $row = mysql_fetch_assoc($result); $i++) {
$results[] = $row;
}
// Re-format the data depending on number of results
$data = array();
if ($i < 14) { // Less than 14 days, show per day
foreach ($results as $row) {
$data[] = $row['data_col'];
}
} else if ($i < 56) { // Less than 8 weeks, show per-week
$thisweek = array();
for ($j = 0; isset($results[$j]); $j++) { // Loop the results
$thisweek[] = $results[$j]['data_col']; // Add result to this week total
if ($j % 7 == 0 && $j > 0) { // Every 7 days...
$data[] = array_sum($thisweek) / 7; // ...calculate the week average...
$thisweek = array(); // ...and reset the total
}
}
// If there is an incomplete week, add it to the data
$data[] = array_sum($thisweek) / count($thisweek);
} else { // 8 weeks or more, show per-month
$thismonth = array();
for ($j = 0; isset($results[$j]); $j++) { // Loop the results
$thismonth[] = $results[$j]['data_col']; // Add result to this month total
if ($j % 28 == 0 && $j > 0) { // Every 28 days...
$data[] = array_sum($thismonth) / 28; // ...calculate the month average...
$thismonth = array(); // ...and reset the total
}
}
// If there is an incomplete month, add it to the data
$data[] = array_sum($thismonth) / count($thismonth);
}
// $data now contains an array from which you should be able to draw your
// graph, where array keys are (sort of) x values and array values are y
// values.
Obviously, this solution assumes a 28-day month - it does not use the calendar, simply the number of days. You could do something horrible involving working out the stats based on some values returned by date() or similar, but this would likely drastically increase the calculation overhead and slow the process down.
Hopefully this will give you a place to start.

Related

Store specific row count with array_push

I'm trying to store a count of specific array items so that I know which row to style in laravel excel
What I would like to do is increase my iterator $rowCount any time I do an array_push, but any time I specifically process an array_push for $groupItem, I want to store the count in $boldRows that way I can apply styling to only those rows.
$allgroupResult= array();
$rowCount = 2; //since I have a sticky header in the excel file I start the count at 2
$boldRows = array();
foreach($prices->groups as $group){
$groupItem = array();
$groupItem["category_code"] = $group->category_code;
$groupItem["category_name"] = $group->category_name;
$groupItem["category_description"] = $group->category_description;
array_push($allgroupResult, $groupItem);
foreach($group->skus as $sku){
$skuItem = array();
$skuItem["identifier"] = $sku->info->identifier;
array_push($allgroupResult, $skuItem);
}
}
category one with 3 products (total of 4 rows) and category two with 2 products (total of 3 rows), would give me 7 total rows starting at row 2. So my expected result with this would be that $boldRows would then contain 2 and 6 for the category rows (because my count starts at 2 then processes 3 products so the next category row is at 6)
How can I properly achieve this?
I would have thought that you just needed to increment the rowcount each time you push a new element to the array and keep track of the rows you want to be in bold...
$rowCount = 2; //since I have a sticky header in the excel file I start the count at 2
$boldRows = array();
foreach($prices->groups as $group){
$groupItem = array();
$groupItem["category_code"] = $group->category_code;
$groupItem["category_name"] = $group->category_name;
$groupItem["category_description"] = $group->category_description;
array_push($allgroupResult, $groupItem);
array_push($boldRows, $rowCount++); // Store count & increment
foreach($group->skus as $sku){
$skuItem = array();
$skuItem["identifier"] = $sku->info->identifier;
array_push($allgroupResult, $skuItem);
$rowCount++; // Just increment count
}
}
You may need to adjust the $rowCount depending on how the rows match the arrays - arrays are 0 based and I don't know how the rows will be based.
Based on PHPExcel Make first row bold and the row number excel row conversion from Convert A to 1 B to 2 ... Z to 26 and then AA to 27 AB to 28 (column indexes to column references in Excel) (modified for PHP), you can then use something like ...
foreach ( $boldRows as $row ) {
$cell_name = excelColumnFromNumber($row)."1";
$objPHPExcel->getActiveSheet()->getStyle( $cell_name )->getFont()->setBold( true );
}
function excelColumnFromNumber($column)
{
$columnString = "";
while ($column > 0)
{
$currentLetterNumber = ($column - 1) % 26;
$columnString = chr($currentLetterNumber + 65) . $columnString;
$column = ($column - ($currentLetterNumber + 1)) / 26;
}
return $columnString;
}

Randomly add 'items' or 'ads' into PHP loop

I have an events loop set up; and I also have an ads loop set up.
I want to inject each 'ad' into the events loop at random points. These loops/arrays have different set ups so can't push into the loop/array.
I had the below set up, which tended to work, but within ad.inc it was getting a random ad... whereas it should be getting the total count of ads and injecting them randomly into the events until that count is reached.
$count = 1;
$total = count($events);
$random = rand(3, $total);
foreach ($events as $event) {
include('./inc/events-item.inc');
if ($count == $random) {
include("./inc/ad.inc");
$random = rand($count, $total);
}
$count++;
}
For example, if my total events count is 30, and my total ads count is 4 then I should see the four ads randomly injected into the 30 events.
Any help?
Create array of all positions for ads. If you have 30 ads - there're 30 positions, from 0 to 29:
$positions = range(0, 29);
// now get 4 random elements from this array:
$rand_positions = array_rand($positions, 4);
// though `array_rand` returns array of keys
// in this case keys are the same as values
// iterate over your events and if counter equals
// to any value in $rand_positions - show ad
$i = 0;
foreach ($events as $event) {
include('./inc/events-item.inc');
if (in_array($i, $rand_positions, true)) {
include("./inc/ad.inc");
}
$i++;
}
You need to randomly select 4 (or however many ads you have) points between 30 (or however many entries you have) other points. Here is a possible solution.
// Set up counts
$entry_count = count($events);
$ad_count = 4;
// Create an array of entry indices, and an array of ad indices
$entry_indices = range(0, $entry_count - 1);
$ad_indices = array();
// Fill the ad indices with random elements from the entry indices
for ($i = 0; $i < $ad_count; $i++) {
$entry = rand(0, count($entry_indices));
array_push($ad_indices, $entry_indices[$entry]);
array_splice($entry_indices, $entry, 1);
}
// Sort it so we only need to look at the first element
sort($ad_indices);
// Iterate through the events
$count = 0;
foreach ($events as $event) {
include('./inc/events-item.inc');
// If we have any ad indices left, see if this entry is one of them
if (count($ad_indices) > 0 && $count == $ad_indices[0]) {
include("./inc/ad.inc");
array_shift($ad_indices);
}
$count++;
}

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.

Fill in absent elements in an array

I have a code that generates total posts from a database per hour for the latest 10 hours. Now, the problem is that only hours with posts are displayed, but that won't work for me because i want to display the whole thing as a chart.
Example of the current array:
array("12"=>"20403",
"15"=>"17017",
"17"=>"84013");
The keys represent the hour in a 24 format. So what i need is a function that fills in the empty hours with 0 value.
Example:
$currenthour=date('H'); // i think it may be based on the latest hour.
array("11"="0",
"12"=>"20403",
"13"=>"0",
"14"=>"0",
"15"=>"17017",
"16"=>"0",
"17"=>"84013",
"18"=>"0",
"19"=>"0",
"20"=>"0");
Thanks!
foreach(range(0, 23) as $hour)
if(!isset($ary[$hour]))
$ary[$hour] = 0;
ksort($ary);
to fill in only last hours you may need something like
function last_hours($hour, $cnt) {
return $hour < $cnt - 1 ?
array_merge(range($hour, 0), range(23, 25 - $cnt + $hour)) :
range($hour, $hour - $cnt + 1);
}
and then
$now = date("G");
$new_array = array();
foreach(last_hours($now, 10) as $hour)
$new_array[$hour] = isset($ary[$hour]) ? $ary[$hour] : 0;
Use array_fill OR do it with a loop (assuming $hours is your array:
$currenthour=date('H');
for($i = $currenthour; $i < 23; $i++)
if(!isset($hours[$i]))
$hours[$i] = 0;
You can simply iterate through the array, and see if the value at the index is set. Like this:
Edit with your the last 10 hours:
$currenthour=date('H')
$beginrange = $currenthour - 10
if ($beginrange =< 0)
$beginrange = 23 + $beginrange
$endrange = $currenthour
//set up the for loop
foreach(range($beginrange, $endrange) as $i)
//check if the element is set
if(!isset($array[$i]))
// set it
$array[$i] = 0;

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.

Categories