Playing around with Modulus Division - php

I'm trying out the modulus division with a foreach loop, and I'm having a bit trouble understanding it.
$counter = 0;
foreach($result as $row){
if(isset($row['username'])){
if (($counter) % 2 == 0){
echo "<tr class=\"r1\"><td class=\"center\">" . $row['username'] . "</td></tr>";
}
else{
echo "<tr class=\"r0\"><td class=\"center\">" . $row['username'] . "</td></tr>";
}
$counter++;
}
}
I want to output:
<tr class="r0">
<td>Bob</td>
<td>Daniel</td>
</tr>
<tr class="r1">
<td>Dylan</td>
<td>Bruce</td>
</tr>
But currently, with my loop, I'm outputting:
<tr class="r1">
<tdBob</td>
</tr>
<tr class="r0">
<td>Daniel</td>
</tr>
<tr class="r1">
<td>Dylan</td>
</tr>
<tr class="r0">
<td>Bruce</td>
</tr>
Can someone explain to me exactly how modulus division works? Thank you.

Here, you want to display two records in one row. Actually modulus division will return the remainder of the division. Try with:
$counter = 0;
$i=1;
foreach($result as $row){
if(isset($row['username'])){
if (($counter) % 2 == 0){ // that is the counter value/2 doesnot returns a remainder ie, divisible by 2, then create another row
if($i%2==0)
{
echo "<tr class=\"r1\">";
}
else
{
echo "<tr class=\"r0\">";
}
}
else{
echo "<td class=\"center\">" . $row['username'] . "</td>";
}
if (($counter) % 2 == 0){ // close the tr if the counter doesnot return remainder
echo "</tr>";
}
$counter++;
$i++;
}
}

I got this to work. My problem was that my array was multidimensional, so I converted it to a single array. Afterwards, I used array_chunks.
$chunks = array_chunk($l, 2);
$i=0;
foreach($chunks as $mychunk){
if($i%2== 0){
echo "<tr class=\"r0\">";
} else { echo "<tr class=\"r1\">"; }
$i++;
foreach($mychunk as $newchunk)
{
echo "<td class=\"center\">" . $newchunk . "</td>";
}
echo "</tr>";
}
For anyone looking to convert multidimensional arrays into single dimensional array:
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}

Related

apply css to specific element in array

I am fetching data of employees from mysql database into array and displaying in table.
everything is working but i want to apply a condition in array that
If salary is greater then 30,000 then change its color to red .
Tried
$q = "select name, salary from array";
$res = mysqli_query($link, $q);
$arr = array();
while ($data = mysqli_fetch_assoc($res)) {
$arr[] = $data;
}
echo '<table class="table table-hover">
<th>Name</th><th>Salary</th>';
$keys = array_keys($arr);
foreach ($keys as $key => $value) {
echo "$value , ";
}
for ($i=0; $i < count($arr); $i++) {
echo '<tr>';
foreach ($arr[$keys[$i]] as $key => $value) {
if ($arr[$keys[$i]['salary']] > 34000) {
echo "<td style='color: red; background-color:pink;'> $key=>$value </td>";
}else{
echo "<td> $key=>$value </td>";
}
}
echo "</tr>";
}
echo '</table>';
this is how my table looks
i want to change color of salary if it is greater than 30,000...
Change
if ($arr[$keys[$i]['salary']] > 34000) {
to
if ($value > 30000) {
I think you just got a little lost when processing an array which contains another arrays. A simple foreach loop is the simplest way of dealing with this.
echo '<table class="table table-hover"><th>Name</th><th>Salary</th>';
foreach ($arr as $row) {
echo '<tr>';
// using a ternary operator here rather than an IF
$style = $row['salary'] > 30000
? ' style="color:red;background-color:pink;"'
: '';
echo "<td>{$row['name']}</td>";
echo "<td $style>{$row['salary']}</td>";
echo '</tr>';
}

Show specific fields in array in php?

echo "<table>";
for ($x=0; $x<=count
($arr['chart_data']); $x++) {
echo "<tr>\n";
foreach($arr['chart_data'][$x] as $key=>$val)
{
echo "<td align='center;' style='color:white;'>". $val . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
I want to show only the first 4 fields in the table. I am decoding a multidimensional array in php. I
Try like
$cnt = 0;
foreach($arr['chart_data'][$x] as $key=>$val) {
if($cnt++ < 4) {
echo "<td align='center;' style='color:white;'>". $val . "</td>\n";
} else {
break;
}
}

Is it possible to dynamically build a table using PHP? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is it possible to dynamically build a table using PHP?
I am using code such as the below to build tables etc. but as there are multiple I was wondering in this case is it possible for the table to be built dynamically based on the SQL query?
For example if I need to build another table then I can copy the below code and just edit the SQL rather than also editing the column headers etc. in the HTML.
Basically some method to simplify the below code so that it is more compact\tidier if being used multiple times on the same page.
Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('core/connection.php');
if($conn){
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT c1, c2, c3, c4
FROM t1
ORDER BY c1
)
WHERE ROWNUM <= 10
");
oci_execute($stid);
echo "<table class='table table-hover '>
<thread>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo "<td>" . $row['0'] . "</td>";
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "</tr>";
unset($row);
}
echo "</tbody>
</table>";
oci_free_statement($stid);
oci_close($conn);
}
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
First example on: http://www.php.net/manual/en/function.oci-execute.php
You could use something like jQuery DataTables, http://datatables.net/ - it will allow you build the table from a JSON-object that you have made with PHP (i.e. by using json_encode() on your SQL result).
Here's my 2 cents on it:
function DisplayRawDataset( $dataset, $connection) {
$res = !is_resource($dataset) ? mysqli_quert($dataset) : $dataset;
if ( !is_resource($res) ) return '';
$i = 0;
$retstr = "";
$retstr .= "<table" border=\"1\" style=\"border-collapse:collapse;\" cellspacing=\"0\" cellpadding=\"2\" >";
while($row = $res->fetch_assoc()){
if($i == 0){
reset($row);
$retstr .= "<tr>";
while(list($key, $val) = each($row)){
$retstr .= "<th><b>".htmlspecialchars($key)."</b></th>";
}
$retstr .= "</tr>";
}
$retstr .= "<tr>";
reset($row);
while(list($key, $val) = each($row)){
$retstr .= "<td>".htmlspecialchars($val)."</td>";
}
$retstr .= "</tr>";
$i++;
}
$retstr .= "</table>";
return $retstr;
}
U could probably do this
$return = "<table class='table table-hover '>
<thread>
<tr>";
foreach(oci_fetch_array($stid, OCI_NUM) as $key){
$return .= "
<th>".$key."</th>
";
}
$return .= "
</tr>
</thread>
<tbody>
<tr>";
foreach(oci_fetch_array($stid, OCI_NUM) as $key => $value) {
$return .= "<td>" . $value . "</td>";
}
$return .= "</tr>
</tbody>
</table>";
}
echo $return;
or something along this line...
I use this....
<?php
/**
#file: tableFunctions.php
#version: 1.0
*/
//Initialize $headersPrinted boolean
$headersPrinted = false;
function obj2Table($obj, $id, $loop)//Passed arguments should include the object, the id for the created table, and '1' for the default first loop
{
global $headersPrinted;
$print = false;
if ($loop == 1)
{
//Setup a table to output the object
echo "<table id=\"$id\" border='.5'>\r\n";
}
//Loop through the object
foreach ($obj as $name => $value)
{
//Check for nested objects
if (is_object($value))
{
//If it is a nested object, feed the child back through
obj2Table($value, $id, 0);
}//end if(is_object)
//Check for nested arrays
elseif (is_array($value))
{
//If it is a nested array, try to feed each array back through
foreach ($value as $arrayKey => $arrayValue)
{
obj2Table($arrayValue, $id, 0);
}
}//end elseif(is_array)
else
{
//Set the $print boolean to true to print the rows once the foreach ends
$print = true;
if (!$headersPrinted)
{
$keys[] = $name;
}
$cells[] = $value;
}//end else
}//end foreach
if ($print)
{
if (!$headersPrinted)
{
echo "<tr>\r\n";
foreach ($keys as $key)
{
echo "<th>$key</th>\r\n";
}
echo "</tr>\r\n";
$headersPrinted = true;
}
foreach ($cells as $cell)
{
echo "<td>$cell</td>\r\n";
}
echo "</tr>\r\n";
}
if ($loop == 1)
{
//Close the table
echo "</table>\r\n";
//Set the $headersPrinted boolean back to false
$headersPrinted = false;
}//end if(initialLoop)
}//end function obj2Table()
?>
The just include that file in your php. In your while statement for the query results, just add each row to an array like this.. $results[] = $row;. After the while loop, then send the results to the function like this... obj2Table($results, 'queryTable', 1);. NOTE: you would need to change your oci_fetch_array to oci_fetch_object.
You can do something like this...
$sql = "SELECT field1 as 'Colunm 1', field2 as 'Colunm 2', fieldn as 'Colunm n' FROM table;";
function buildTable($sql){
$tab = "";
$head = "";
$body = "";
if (is_string($sql) && $sql !== "") {
$qry = mysql_query($sql);
while ($fet = mysql_fetch_assoc($qry)) {
if ($head == "") {
$head = "<tr>";
foreach ($fet as $key => $val) {
$head .= "<th>{$key}</th>";
}
$head .= "<tr>";
}
$body .= "<tr>";
foreach ($fet as $key => $val) {
$body .= "<td>{$val}</td>";
}
$body .= "</tr>";
}
return "<table><thead>{$head}</thead><tbody>{$body}</tbody></table>";
}
}
echo buildTable($sql);
Yes , it is possible , but you are doing it wrong. HTML that you echo is not valid (some HTML elements have a required closing tag like <table></table> so you should output <table> and </table> in one echo). One of the options for you is to assign your dynamic HTML to a value and then echo the valid HTML.
$buffer = "<table class='table table-hover '>
<thread>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
$buffer .= "<tr>
<td>" . $row['0'] . "</td>
<td>" . $row['1'] . "</td>
<td>" . $row['2'] . "</td>
<td>" . $row['3'] . "</td>
</tr>";
unset($row);
}
$buffer .= "</tbody>
</table>";
echo $buffer;

PHP Sorting files in a table

Currently I have a table order by
A B C D
E F G H
but I would like to order the table by
A E
B F
C G
D H
Code:
for($i=0;$i<=count($aFiles);$i++)
{
if($i%5==0)
{
echo "</tr><tr>";
}
echo '<td><a>'.$aFiles[$i].'</a></td>';
}
echo '</tr>';
echo '</table>';
Files are already sorted a-z in $aFiles.
$aFiles = array('a','b','c','d', 'e', 'f', 'g');
$iColumnNumber = 2;
$iRowMaxNumber = ceil(count($aFiles) / $iColumnNumber);
$iTableRow = 0;
$iTableColumns = 1;
$aTableRows = array();
// make array with table cells
foreach ($aFiles as $sFile)
{
if ($iTableRow == $iRowMaxNumber)
{
$iTableRow = 0;
$iTableColumns++;
}
if (!isset($aTableRows[$iTableRow]))
{
$aTableRows[$iTableRow] = array();
}
$aTableRows[$iTableRow][] = '<td>' . $sFile . '</td>';
$iTableRow++;
}
// if there is odd number of elements
// we should add empty td elements
for ($iTableRow; $iTableRow < $iRowMaxNumber; $iTableRow++)
{
if (count($aTableRows[$iTableRow]) < $iTableColumns)
{
$aTableRows[$iTableRow][] ='<td>empty</td>';
}
}
// display table
echo '<table>';
foreach ($aTableRows as $aTableRow)
{
echo '<tr>';
echo implode('', $aTableRow);
echo '</tr>';
}
echo '</table>';
Simple Approach using HTML trick:
echo '<div class="tbl_group"><table>';
for($i=0;$i<=count($aFiles / 2);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
echo '<div class="tbl_group"><table>';
for($i=$aFiles / 2;$i<=count($aFiles);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
For the CSS:
.tbl_group {
float: left;
}
With this approach, 2 tables are built side-by-side. float: left CSS will auto adjust the position of the tables.
Assuming you know the number of rows you want, you don't need to resort anything, just add some logic in your loop that generates the <td>s :
$size = count($aFiles);
echo '<table><tr>';
for($i=0;$i<=ceil($size/2);$i++) {
if($i%2==0) {
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo "</tr><tr>";
} else {
if(isset($aFiles[$i+floor($size/2)])) {
echo '<td><a>'.$aFiles[$i+floor($size/2)].'</a></td>';
}
}
}
echo '</tr></table>';
Example bellow also works with associative array + arrays with odd elements.
Code for associative AND indexed array :
$aFiles = ['test'=>"A","B",'c'=>"C","D","E","F",'g'=>"G","H",'iii'=>"I"];
$aKeys = array_keys($aFiles);
$aRows = ceil(count($aFiles) / 2);
echo '<table>';
for($i=0; $i < $aRows; $i++) {
echo
'<tr>' .
' <td>' . $aFiles[$aKeys[$i]] . '</td>' .
' <td>' . (isset($aKeys[$i+$aRows]) ? $aFiles[$aKeys[$i+$aRows]] : 'empty') . '</td>' .
'</tr>';
}
echo '</table>';
Code for ONLY indexed array :
$aFiles = ["A","B","C","D","E","F","G","H","I"];
$aRows = ceil(count($aFiles) / 2);
echo "<table>";
for($i=0; $i < $aRows; $i++) {
echo
"<tr>" .
" <td>" . $aFiles[$i] . "</td>" .
" <td>" . (isset($aFiles[$i+$aRows]) ? $aFiles[$i+$aRows] : "empty") . "</td>" .
"</tr>";
}
echo "</table>";
Output for both examples is identical :
<table>
<tr>
<td>A</td>
<td>F</td>
</tr>
<tr>
<td>B</td>
<td>G</td>
</tr>
<tr>
<td>C</td>
<td>H</td>
</tr>
<tr>
<td>D</td>
<td>I</td>
</tr>
<tr>
<td>E</td>
<td>empty</td>
</tr>
</table>
Not optimized, but this should more or less work:
$aFiles = array ("A","B","C","D","E","F","G","H","I","J","K","L","M","N",);
$rows = 4;
$columns = floor((count($aFiles)/$rows))+1;
echo '<table>';
for ($i=0;$i<$rows;$i++) {
echo '<tr>';
for ($j=0;$j<$columns;$j++) {
echo '<td>';
if (isset($aFiles[$i+$j*$rows]))
echo $aFiles[$i+$j*$rows];
else
echo " ";
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
You can change the number of rows if you want.
Try this one. Assume that your $aFiles contains a-z alphabetically.
for ($i = 0; $i < count($aFiles/2); $i++){
echo '<tr><td><a>'.$aFiles[$i].'</a><td><td><a>'.$aFiles[$i+13].'</a><td></tr>'
}

Looping through Array in multiple <td> cells

Lets say I have an array
$aSomeArray = array("1","2","3","4","5","6","7","8","9","10","11","12");
Now displaying one array value in one table row is easy like this
echo "<table>";
foreach ($aSomeArray as $iSomeArrayKey => $iSomeArrayValue)
{
echo "<tr>";
echo "<td>".$iSomeArrayValue."</td>";
echo "</tr>";
}
echo "</table>";
But I want to display the values in table format like this
1 2 3 4
5 6 7 8
9 10 11 12
How can I achieve this ?
Edited, this works:
$aSomeArray = array("1","2","3","4","5","6","7","8","9","10","11","12");
$i = 0;
echo "<table>\r\n";
foreach ($aSomeArray as $aSomeArrayKey => $aSomeArrayValue)
{
if (($i % 4) == 0) echo "\t<tr>\r\n";
echo "\t\t<td>" . $aSomeArrayValue . "</td>\r\n";
if (($i % 4) == 3) echo "\t</tr>\r\n";
$i++;
}
echo "</table>\r\n";
Just a thought which seems nicer IMHO.
<?php
$aSomeArray = array("1","2","3","4","5","6","7","8","9","10","11","12");
function createMatrix($width, $array)
{
$newArray = array();
$temp = array();
$count = 1;
foreach($array as $key => $value)
{
$temp[] = $value;
if(($count++ % $width) == 0)
{
$newArray[] = $temp;
$temp = array();
}
}
if( count($temp) > 0)
{
$newArray[] = $temp;
}
return $newArray;
}
will create a matrix array of variable $width
You can then use that data as a double for-each like this:
$matrix = createMatrix(2, $aSomeArray );
foreach($matrix as $row)
{
echo "<tr>\n";
foreach($row as $td)
{
echo "\t<td>{$td}</td>\n";
}
echo "</tr>\n";
}
Which produces:
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>11</td>
<td>12</td>
</tr>
Just do a running count. So before the foreach set $i = 1 and every fourth result, reset the count to $i = 1 and then end the row and re-open a new row.
$aSomeArray = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13");
$columns = 4; // The number of columns to shown
echo "<table>";
$i = 0;
$trOpen = false; // just a flag if <tr> has been closed (paired with </tr>) or not.
foreach ($aSomeArray as $item) {
if ($i % $columns == 0) {
echo "<tr>";
$trOpen = true;
}
echo "<td>" . $item . "</td>";
if (($i + 1) % $columns == 0) {
echo "</tr>";
$trOpen = false;
}
$i++;
}
if ($trOpen) {
echo "</tr>"; // add '</tr>' if it is not yet added.
}
echo "</table>";
$i=1;
echo "<tr>";
foreach ($aSomeArray as $aSomeArrayKey => $aSomeArrayValue)
{
echo "<td>".$aSomeArrayValue."</td>";
$i++;
if($i%4==0){
echo "<tr></tr>";
}
}
echo "</tr>";
It will also work for the indivisible by 4 number of elements.
echo "<table>";
echo "<tr>";
foreach ($aSomeArray as $aSomeArrayKey => $aSomeArrayValue)
{
echo "<td>".$aSomeArrayValue."</td>";
if($aSomeArrayValue % 4 == 0)
echo "</tr><tr>";
}
echo "</tr>";
echo "</table>";
Try this code
<?php
$i=0;
echo"<table>";
echo"<tr>";
foreach($aSomeArrayas as $val)
{
if($i %4 ==0)
{
echo"</tr><tr> <td> $val</td>";
}
else
{
echo"<td> $val </td>";
}
$i++;
}
echo"</tr>";
echo"</table>";
?>

Categories