Insert data and generate grid dynamically in codeigniter - php

I need some ideas for to do the follow:
I need to build a table dynamically and insert and update the data in the db with codeigniter.
$dates=array (date1, date2, ......daten) (cols)
$people=array(name1, name2, ......namen) (rows)
date1 date2 date3
name1 3 5 8
name2 2 6 9
name3 5 5 1
name4 10 2 8
In the db I need to register:
name1, date1 and 3
name1, date2 and 5
name2, date1 and 2
....

This solution has worked well for me, you just need to collate your array carefully.
(Taken from the PHP Cookbook)
function pc_grid_horizontal($array, $size) {
// compute <td> width %ages
$table_width = 100;
$width = intval($table_width / $size);
// define how our <tr> and <td> tags appear
// sprintf() requires us to use %% to get literal %
$tr = '<tr align="center">';
$td = "<td width=\"$width%%\">%s</td>";
// open table
$grid = "<table width=\"$table_width%%\">$tr";
// loop through entries and display in rows of size $sized
// $i keeps track of when we need a new table tow
$i = 0;
foreach ($array as $e) {
$grid .= sprintf($td, $e);
$i++;
// end of a row
// close it up and open a new one
if (!($i % $size)) {
$grid .= "</tr>$tr";
}
}
// pad out remaining cells with blanks
while ($i % $size) {
$grid .= sprintf($td, ' ');
$i++;
}
// add </tr>, if necessary
$end_tr_len = strlen($tr) * -1;
if (substr($grid, $end_tr_len) != $tr) {
$grid .= '</tr>';
} else {
$grid = substr($grid, 0, $end_tr_len);
}
// close table
$grid .= '</table>';
return $grid;
}
For example, let’s print the names of the 50 U.S. states in a six-column table:
$query = $this->db->query('SELECT * FROM `states`');
$states = $query->result_array();
// generate the HTML table
$grid = pc_grid_horizontal($states, 6);
print $grid;

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

Add a different cell & formula for each row in parsed table

I'm currently parsing specific columns of a table via simple_html_dom. Which works fine. I now want to add an extra column after that group with a calculation-formula for each row. It is also important that it works with various row-numbers, cause each table could have a different amount of rows.
It should work like this:
<external htmt table parsed via simple_html_dom>< - should be added into the array ->
row(1) = column1 | column2 | column3 | column4 | do nothing this is header
row(2) = cell1 | cell2 | cell3 | cell4 | sum cell 2 to 4 of row(2)
row(n) = cell1 | cell2 | cell3 | cell4 | sum cell 2 to 4 of row(n)
I thought about adding Dom Document into the code when I echo the $td cells.
// cells of row
echo '<td>' . $td .'</td>';
// now new cell at the end of row
echo '<td>';
// now adding calculation via Dom
$file = $DOCUMENT_ROOT. 'URL';
$doc = new DOMDocument;
$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
// Sum Column 2 + 3 + 4 of row 2 (in this example, different below)
print $xpath->evaluate('(//table/tr[2]/td[2])+(//table/tr[2]/td[3])+(//table/tr[2]/td[4])');
// closing cell and row
echo ' mio $</td>';
echo '</tr>';
This actually works, but obviously only with row 2. So each row now has the sum for row 2 at the end. Is there any way to calculate it for each row differently?
This is the whole code currently
// Table 6 - Contracts
$table6 = $html->find('table', 6);
$rowData1 = array();
$columnNumbers = [ 3, 4, 5, 6];
foreach($table6->find('tr') as $row) {
// initialize array to store the cell data from each row
$flight1 = array();
foreach($row->find('td') as $columnNumber => $cell) {
// push the cell's text to the array
if ( in_array( $columnNumber, $columnNumbers ) ) {
$flight1[] = $cell->plaintext;
}
}
foreach($row->find('th') as $columnNumber => $cell) {
// push the cell's text to the array
if ( in_array( $columnNumber, $columnNumbers ) ) {
$flight1[] = $cell->plaintext;
} }
$rowData1[] = $flight1;
}
foreach ($rowData1 as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '<td>';
// now adding calculation via Dom
$file = $DOCUMENT_ROOT. 'URL';
$doc = new DOMDocument;
#$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
// Sum Column 4 + 5 + 6 of row 2
print $xpath->evaluate('(//table[td/u/b/.="Contracts"]/tr[2]/td[4])+(//table[td/u/b/.="Contracts"]/tr[2]/td[5])+(//table[td/u/b/.="Contracts"]/tr[2]/td[6])');
// closing cell and row
echo ' mio $</td>';
echo '</tr>';
}
echo '</table>

Function to create an Alphabetical Table List with Indexes from an Array

given an array, is there a way to output a 4 column html table with an alphabetically-sorted list of the array's contents with the first index letter of the alphabet highlighted (only if there is an element in the array that starts with any given letter of the alphabet)?
In other words, say I have the array:
$array = ('apple','pear','banana','pomegranate','orange','peach','clementine');
I want an output like this:
_________________________________________
|A |C |P |O |
|apple |clementine |pear |orange |
|B |O |pomegranate | |
|banana |orange |peach | |
------------------------------------------
How can I do that?
I was looking for a ready-made function to generate such an alphabetic list from an array and display such list in a table with index letters, like this:
Since I couldn't find one I wrote one and I am posting here for everyone to use:
function alphaTable($array,$columns=NULL) {
$i = 0;
$index_css_style_name = 'alphaindex';
$entry_css_style_name = 'alphaentry';
sort($array); // sort our array alphabetically
$list = array(); // create empty array which will contain the alphabetic index list
while ( $i < count($array) ) { // cycle through our array
$index[$i] = substr($array[$i],0,1); // get first character of entry
if ( $i == 0 && is_numeric($index[$i]) ) {
$list[] = ' <div class="'.$index_css_style_name.'">[0-9]</div>'."\n"; // add the default index for numbers/digits
$list[] = $names[$i][0].'<br />'; // add the regular non-index entries to our alphabetic index list array
} else if ( $i > 0 && !is_numeric($index[$i]) && $index[$i] != $index[($i - 1)] ) { // if it is not numeric then it's a letter of the alphabet
$list[] = ' <div class="'.$index_css_style_name.'">'.strtoupper($index[$i]).'</div>'."\n"; // add the uppercase letter of the current index
$list[] = $names[$i][0].'<br />'; // add the regular non-index entries to our alphabetic index list array
} else {
$list[] = $names[$i][0].'<br />'; // add the regular non-index entries to our alphabetic index list array
}
$i++;
}
unset($i);
// check if the function calls specifies a numnber of desired columns for the table
if ( !isset($columns) )
$columns = 4; // if number of columns is not specified, let's set it to 4
$epc = count($list) / $columns; // get the entries per columns
$epc = ceil($epc); // round it up!!
$i = 1; // let's start at 1 so when we multiply by 0 it doesn't return 0
$e = 0;
$table = "\n".'<table border=1>'."\n";
$table .= ' <tr valign="top">'."\n";
while ( $i <= $columns ) { // less or equal to (because we started at 1)
$table .= ' <td>'."\n";
while ( $e < ($epc * $i) ) { // we increment e within the i while loop so that we can continue with the entries in the table
if ( !empty($list[$e]) )
if ( substr_count($list[$e],$index_css_style_name) > 0 ) // to prevent double <span> tags we check whether our desired index css styling is present
$table .= $list[$e]; // if it's an index we just add it to the table
else
$table .= ' <span class="'.$entry_css_style_name.'">- '.$list[$e].'</span>'."\n"; // if it's an entry we style it and add it to the table
$e++;
}
$table .= ' </td>'."\n";
$i++;
}
$table .= ' </tr>'."\n";
$table .= '</table>'."\n";
unset($i);
unset($e);
return $table;
}
Just trying to give back to the community that has helped me so much when I was stuck on something.
Feel free to use.
You are welcome ;-)

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

Spliting PHP/MySQL data into 3 columns

I need to create 3 HTML columns in PHP with data returned from MySQL. I would like the data split evenly between all 3 columns... How would I go about doing this?
You could try doing something like this:
$result = mysql_query("SELECT value FROM table");
$i = 0;
echo '<table><tr>';
while ($row = mysql_fetch_row($result)){
echo '<td>' . $row[0] . '</td>';
if ($i++ == 2) echo '</tr><tr>'
}
echo '</tr></table>';
note this table has the values ordered like
1 2 3
4 5 6
7 8 9
If you wanted it vertically like
1 4 7
2 5 8
3 6 9
Then you should do something like
$result = mysql_query("SELECT value FROM table");
$data = Array();
while ($row = mysql_fetch_row($result)) $data[] = $row;
for ($i = 0; $i < count($data) / 3; $i++){
echo '<table><tr>';
for ($j = 0; $j < 3; $j++){
echo '<td>' . $data[ $i + $j * 3] . '</td>';
}
echo '</tr><tr>'
}
echo '</tr></table>';
You can create an HTML table and then use a PHP foreach loop to loop through the MySQL result set and put each field in its own table. At the end of each record returned by the MySQL query, end the table row and start a new one.
A small detail, if return more entries than the "fetch_row" use "break", based on the answer from #Robbie: Spliting mysql data in 3 columns error -3-columns-error

Categories