This should be a fairly simple problem, however I cannot for the life of me get it to work right.
I have JSON data in the form of an array like so and I am trying to generate a 2-column table where every 2 elements in the array take up a row.
[
{
"type": "Ground",
"field_location": "",
"field_user": "",
},
{
"type": "Water",
"field_location": "",
"field_user": "",
},
{
"type": "Sewer",
"field_location": "",
"field_user": "",
},
{
"type": "Tap",
"field_location": "",
"field_user": "",
}
]
I have overly simplified the code, however the function currently looks as follows.
function generateHtml($jsonDoc){
$html = "";
$html .= "<table>";
$count = 0;
foreach ($jsonDoc as $key => $value) {
$count ++;
if ($count % 2 == 0)
$html .= "<tr>";
$html .= "<td>";
foreach ($value as $key => $val) {
if(!empty($val))
$html .= $key.":".$val."<br />";
}
$html .= "</td>";
if ($count % 2 == 0)
$html .= "</tr>";
// $count ++;
}
$html .= "</table>";
print($html);
}
The resulting HTML output always seems to come out as follows and I cannot seem to understand what is missing.
<table>
<tr>
<td>Ground</td>
</tr>
<tr>
<td>Water</td>
</tr>
<tr>
<td>Sewer</td>
</tr>
<tr>
<td>Tap</td>
</tr>
</table>
as opposed to
<table>
<tr>
<td>Ground</td>
<td>Water</td>
</tr>
<tr>
<td>Sewer</td>
<td>Tap</td>
</tr>
</table>
```
which is what I am looking for.
One simple(r) way to achieve this, would be to use array_chunk to split your original data into an array of arrays, and then just use two nested loops to generate the output.
In the outer loop, you create the table row (output <tr> before, and </tr> after), and in the inner loop, you create a table cell for each item.
function generateHtml($jsonDoc){
$data = array_chunk($jsonDoc, 2); // split this into an array of arrays,
// containing two of the items each
$html = '<table>';
foreach ($data as $row) { // loop over the first level
$html .= '<tr>';
foreach ($row as $cell) { // loop over the second level
$html .= '<td>'.$cell->type.'</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
print($html);
}
Try this
function generateHtml($jsonDoc){
$html = "";
$html .= "<table>";
$count = 1;
foreach ($jsonDoc as $key => $value) {
//$count ++;
if ($count % 2 != 0)
$html .= "<tr>";
$html .= "<td>";
foreach ($value as $key => $val) {
if(!empty($val))
$html .= $key.":".$val."<br />";
}
$html .= "</td>";
if ($count % 2 == 0)
$html .= "</tr>";
$count ++;
}
$html .= "</table>";
print($html);
}
Related
I have written a function to display the data fetched from MySQL database using PHP mysqli_query( $db_conn, $sql ); when I am calling the following display function first row of the data is not displayed. Please suggest how can I get the first row.
function display_data($retval) {
$output = '<table border="1">';
foreach($retval as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
Code for display data
if (isset( $_POST['submit'])){
$_date = $_POST["date"];
//echo $_date;
$resultArray = array();
$sql = "SELECT * FROM outstanding WHERE ondate='$_date' ";
};
/*echo json_encode($retval);*/
$retval = mysqli_query( $db_conn, $sql );
display_data($retval);
}
EDIT 2:
I was able to achieve this by the following code, please suggest if there are any better methods to display in HTML/web page.
//code to display data in table form
function display_data($retval)
{
$output = '<table border="1">';
foreach ($retval as $key => $var)
{
echo $key;
if ($key === 0)
{
$output .= '<tr>';
foreach ($var as $k => $v)
{
$output .= '<th><strong>' . $k . '</strong></th>';
};
$output .= '</tr>';
};
$output .= '<tr>';
foreach ($var as $k => $v)
{
if ($key === 0)
{
$output .= '<td>' . $v . '</td>';
echo $v;
}
else
{
$output .= '<td>' . $v . '</td>';
};
};
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
The reason why you cannot see the first row is that you never display it. If the iteration is on the first row, you only display the header, but you skip the data.
foreach ($var as $k => $v) {
if ($key === 0) {
// If this is the first row, you display the key, but not the value.
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
Your suggested solution is the correct one. You need to loop the first row twice. Once to display the header and then once to display the data.
function display_data1($retval) {
$output = '<table border="1">';
foreach ($retval as $key => $var) {
if ($key === 0) {
// If key is 0, meaning first row...
$output .= '<thead><tr>';
// create new HTML row and loop the first MySQL row
foreach ($var as $k => $v) {
$output .= '<th>' . $k . '</th>';
}
$output .= '</tr></thead>';
}
// Then loop as normal all rows including the first one.
$output .= '<tr>';
foreach ($var as $k => $v) {
$output .= '<td>' . $v . '</td>';
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
I need to get a table with simple html dom parser, clean it (remove attr and spaces), then output it again.
My question is, how can i loop through with PHP and output the TH and TD in one sequence?
At the moment it will handle the TH as a TD but i like to have the TH set correctly.
<table>
<tbody>
<tr>
<th>Date1</th>
<th>Date2</th>
</tr>
<tr>
<td>01.01.2019</td>
<td>05.01.2019</td>
</tr>
</tbody>
</table>
require('simple_html_dom.php');
$html = file_get_html( "template.html" );
$table = $html->find('table', 0);
$rowData = array();
foreach($table->find('tr') as $row) {
$keeper = array();
foreach($row->find('td, th') as $cell) {
$keeper[] = $cell->plaintext;
}
$rowData[] = $keeper;
}
echo '<table">';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
I tried something with the foreach, but i think i need something else.
ty for your ideas.
greet;s
You can do it like this:
require('simple_html_dom.php');
$html = file_get_html( "template.html" );
$table = $html->find('table', 0);
$rowData = array();
foreach($table->find('tr') as $row) {
$keeper = array();
foreach($row->find('td, th') as $cell) {
$data = array();
$data['tag'] = $cell->tag; //stored Tag and Plain Text
$data['plaintext'] = $cell->plaintext;
$keeper[] = $data;
}
$rowData[] = $keeper;
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<'.$td['tag'].'>' . $td['plaintext'] .'</'.$td['tag'].'>'; // Tag used
echo '</tr>';
}
echo '</table>';
You would need to store the type of cells, it would be enough to store them at row level as they should all be the same. Then when you rebuild the rows, use this type as the cell type to create...
foreach($table->find('tr') as $row) {
$keeper = array();
foreach($row->find('td, th') as $cell) {
$keeper[] = $cell->plaintext;
}
// Type is the 2nd & 3rd chars of html - <th>content</th> gives th
// Store type and cell data as two elements of the rowData
$rowData[] = ["type" => substr($cell,1,2), "cells" => $keeper];
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
// Loop over the cells of the row
foreach ($tr["cells"] as $td)
// Output row type as the element type
echo "<$tr[type]>" . $td ."</$tr[type]>";
echo '</tr>';
}
echo '</table>';
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>';
}
I have an array that i pull from a database that looks like this
id - name - shortlink - downloadurl - count - date
Now I want to display that array as a table so the administartor of the site can se the content of the database. For that, I'm using this code:
function build_table($array){
// start table
$html = '<table id="usertable">';
// header row
$html .= '<tr class="header">';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
And it works great.
The problem is that i wan't do display some of the columns with a different code. E.g. 'downloadurl' which is an webadress, i want to make clickable. I just can't figure out how to split up the function so that i can write the code for the individual columns.
You could try something similar to the following:
using conditionals
This is probably the most straight forward way to go about handling different attributes per column - not without its drawbacks (noted below)
// data rows
foreach( $array as $key => $value) {
$html .= '<tr>';
foreach($value as $key2 => $value2) {
if ($key2 == 'downloadurl') {
$html .= '<td>Download</td>';
} else {
$html .= '<td>' . $value2 . '</td>';
}
}
$html .= '</tr>';
}
using switch statement
If you decide on this route, it may be a bit easier to manage in the long run as if () elseif () else() can become difficult to read over time.
foreach($value as $key2 => $value2) {
switch($key2) {
case 'downloadurl':
$html .= '<td>Download</td>';
break;
default:
$html .= '<td>' . $value2 . '</td>';
}
}
use this function to generate urls:
function getURL($downloadURL)
{
$html = "<a href = '$downloadURL'>Download</a>";
return $html;
}
And your function build_table():
function build_table($array){
// start table
$html = '<table id = "usertable">';
// header row
$html .= '<tr class = "header">';
foreach($array[0] as $key => $value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key => $value){
$html .= '<tr>';
foreach($value as $key2 => $value2){
$value2 = ($key2 == 'downloadurl') ? getURL($value2) : $value2;
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
I have an Array of Arrays and Want to create a Tabular data layout. This is not the exact code, as how their generated is quite the cluster (Coming from COBOL interaction) but this should give me enough to make it work if someone can think of a clean way to code this.
array(
Array(847.0, 97010, 11)
Array(847.0, 97012, 10)
Array(847.1, 97010, 08)
Array(847.1, 97012, 14)
)
So I want to put these into a Table that looks something like
97010 97012
847.0 11 10
847.1 08 14
The first 2 elements of the arrays will always be the two axis and the 3rd the contents of the table.
Any Suggestions? thanks!
$table = array();
$columns = array();
// copy the array (x, y, value) into a table
// keeping track of the unique column names as we go
foreach ($dataSet as $point) {
// provided sample data used floats, ensure it is a string
$x = strval($point[0]);
$y = strval($point[1]);
$data = $point[2];
if (!isset($table[$x])) {
$table[$x] = array();
}
$table[$x][$y] = $data;
// quick and dirty style 'unique on insert'
$columns[$y] = true;
}
// switch the column names from title => true to just titles
$columns = array_flip($columns);
// Display the table
echo '<table>';
// Header row
echo '<tr>';
echo '<th> </th>';
foreach ($columns as $columnTitle) {
echo '<th>' . $columnTitle . '</th>';
}
echo '</tr>';
// Bulk of the table
foreach ($table as $rowTitle => $row) {
echo '<tr>';
echo '<th>' . $rowTitle . '</th>';
foreach ($columns as $columnTitle => $junk) {
if (isset($row[$columnTitle]) {
echo '<td>' . $row[$columnTitle] . '</td>';
} else {
// Handle sparse tables gracefully.
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
From what I understood:
$arr[847.0][97010] = '11';
$arr[847.0][97012] = '10';
$arr[847.1][97010] = '08';
$arr[847.1][97012] = '14';
And you may create a table:
$result = "<table>";
foreach($arr as $row_key => $row) {
$result .= "<tr>";
foreach($row as $column_key => $data) {
$result .= "<td>".$data."</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
echo $result;