Store specific row count with array_push - php

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;
}

Related

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++;
}

export excel sheet using phpexcel to set rows and columns

i have the database
roll_no
201261001
201261002
201261003
201261004
201261005
201261006
201261007
201261008
I need to export to excel sheet in 6 rows and 12 columns format
output
201261001
201261002
201261003
201261004
201261005 201261008
201261006 201261007
The remaining cells should be empty
Something like the following will iterate over the resultset from your database query, and write to the appropriate row/column in the spreadsheet. It uses the modulus operator to determine when a column has been filled to 6 rows, and then increments the column and resets the row number ready for the next record.
$row = 1;
$column = 'A';
$record = 0;
while ($data = mysqli_fetch_assoc) {
if (($record > 0) && ($record % 6 == 0)) {
$row = 1;
$column++;
}
$objPHPExcel->getActiveSheet()->getCell($column.$row)->setValue($data['roll_no']);
$row++;
$record++;
}

Loop through mysql table row and check if any column matches a set number in php

Im trying to loop through a mysql table and check if a row contains the number I specify:
Here is what I have:
mysql table with numbers:
mysql table:
no1|no2|no3|no4|no5
1 3 5 2 6
4 7 8 9 8
2 6 9 1 0
...
For Example: I have number
4 5 3 7
So in the first row i should get a total of 2 as there are numbers 3 and 5 first row and this numbers are in the number I have specified.
In the second row I should get a total of 1 as only a 4 is in the row and the number i have specified.
And in the last row total should be 0 as there are no matches.
I hope its clear.
I have tried the following but it dont work I hope someone can help me work it out thanks in advance.
$lottono1=4;
$lottono2=5;
$lottono3=3;
$lottono4=7;
$no1 = 0;
$no2 = 0;
$no3 = 0;
$no4 = 0;
do { ?>
// i done the following if code for each numbers but
//putting this only to take less space
if (($row_Recordset1['no1']=$lottono1) || ($row_Recordset1['no1']=$lottono2) || ($row_Recordset1['no1']=$lottono3) || ($row_Recordset1['no1']=$lottono4)) {
$no1=1;
}
while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
select *,
if(no1 in (4,5,3,7),1,0)+
if(no2 in (4,5,3,7),1,0)+
if(no3 in (4,5,3,7),1,0)+
if(no4 in (4,5,3,7),1,0)+
if(no5 in (4,5,3,7),1,0) as found
from table
Well for one, your operators are wrong in your "if" conditions (you're setting rather than comparing).
Regardless i'd do something more like:
$numbers_to_match = array(4,5,3,7) ;
$query = mysql_query("select * from `table` where ____",connection_here);
$matches[] = array();
$i=0;
while($r=mysql_fetch_array($query)){
$matches[$i]=0;
foreach($r as $val){
if (in_array($val,$numbers_to_match)){
$matches[$i]++;
}
}
$i++;
}
print_r($matches);
Untested, but this should give you an array that lists the number of matches for each row
To accomplish with PHP/MySQL you can do the following:
$query = 'SELECT * FROM table';
$result = mysql_query($query) or die();
$matchValues = array(4,5,3,7);
while($row = mysql_fetch_array($result)){
$counter = 0;
foreach($matchValues as $value)
{
if(in_array($value, $row))
{
$counter++;
}
}
print "Searched row and found $counter matches<br/>";
}

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

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.

Empty results when I store records in array, repeat them to reach certain nr and use foreach to display them

This is what my code does:
it gets 4 rows from my table, stores them in an array, repeats them untill they reach 20 inside that array then echo's them whit a foreach loop... problem is i get an empty result at the end of each foreach cycle of the 4 results.
$result = mysql_query("SELECT * FROM ".$table."");
$row_nr = mysql_num_rows($result); // Find out how many rows I have in the table, lets say 4
while($rows = mysql_fetch_assoc($result)){
$arrayrows[] = $rows; // Put my 4 rows in the array
}
// Now I multiply nr. of rows to reach desired number which is 20
$dbRow=0;
for($n=0; $n <= 20; $n++)
{
if($dbRow > $row_nr) $dbRow = 0;
$fullarrayrows[$n] = $arrayrows[$dbRow];
$dbRow++;
}
// after some php pagination code I slice the array:
$arrayslice = array_slice($fullarrayrows, $offset, $rowsperpage);
// Now i display my array
foreach($arrayslice as $slice)
{
echo ''.$slice['name'].'';
echo '<br />';
}
Problem is I get some empty records in the foreach
name1name2name3name4HERE I GET THE EMPTY ENTRYname1name2name3name4AGAIN I GET THE EMPTY ENTRY
... and so on, at the end of each cycle
Thank you very much , please give me an ideea of what's wrong:)
$dbRow indexes start at 0 and end at 3
but $row_nr equals 4
so change this line
if($dbRow > $row_nr) $dbRow = 0;
to
if($dbRow >= $row_nr) $dbRow = 0;

Categories