Building a Table of Data with an Array of Arrays - php

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;

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

Display PHP Query results in table regardless of # of columns returned?

So I'm exploring the wonderful world of PHP and I'm still creating very dirty, poorly build code but I'm trying to get better! So my question is as follows:
Is there a way to automatically calculate the columns in the result set and spit out a pretty HTML table regardless of query used?
Here the current code:
<?php
include '../includes/connect.php';
include '../includes/queries.php';
$stid = oci_parse($conn, $export);
oci_execute($stid);
echo "<table class='pure-table pure-table-striped' style='font-size:11px;'><thead><tr><th>Name</th><th>File Name</th><th>Export Date</th></tr></thead>";
while (oci_fetch($stid)) {
echo "<tr><td>" . oci_result($stid, 'DISPLAY_NAME') . "</td>";
echo "<td>" . oci_result($stid, 'LAST_EXPORT_FILE') . "</td>";
echo "<td>" . oci_result($stid, 'LAST_EXPORT_DATE') . "</td></tr>";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
I'd like to use the same table every time, but just have it auto detect column header names and number of columns and return it in a table.
Is it possible or does it make sense?
I do exactly that using PDO.
$out = '';
$q = $conn->prepare($SQL);
if ($q->execute()) {
$rows = $q->fetchAll();
if (!empty($rows)) {
//We have something
$out .= "<table class='pure-table pure-table-striped' style='font-size:11px;'>";
$first = true;
//iterate on rows
foreach($rows as $row) {
//Clean out all the numeric keys - stops duplicate values
foreach ($row as $key => $value) {
if (is_int($key)) {
unset($row[$key]);
}
}
//header
if ($first) {
//write header
$out .= '<thead><tr>';
foreach ($row as $key => $value) {
$out .= '<th>' . $key . '</th>';
}
$out .= '</tr></thead>';
$first = false;
}
//write line
$out .= '<tr>';
foreach($row as $key => $value) {
$out .= '<td>' . $value . '</td>';
}
$out .= '</tr>';
}
$out .= '</table>';
}
}
echo ($out);

Add links to data in HTML table Created using PHP and a MYSQL database

I am trying to pull data from a table in PHPmyadmin and convert it to an HTML table based on some customer form input which filters out unneeded rows. The code below does that fine. The issue is that two of my columns need to contain links.
It would be easy enough to use PHP to change the table data into the link using a strtolower() and str_replace() to remove spaces, then concatinating the "www.website.com/" and the ".html". But I'm using a foreach loop to get all of the rows that I need and I don't know how to only alter one value per row.
I have tried using "Broswer Display Transformations" and "Input Transformations" in PHPmyadmin, but that only seems to affect the data in PHPmyadmin and not when I access the data via PHP.
My current code:
//* Code for Table
$query = "SELECT $searchFields FROM `hose_reels` $searchPhrase ORDER BY `model` ASC";
$result = mysqli_query($cxn,$query);
if ($row[$key] != "0") {
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
echo "<th>" . $key . "</th>";
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
echo "<td>$row[$key]</td>";
}
echo "</tr>";
}
echo "</table>";
}
else {
echo "<p>No results match your selection. Please broaden your search.</p>";
}
Just add <a> tag in your php code. Below is the code. One more thing you have error in echo "<td>$row[$key]</td>"; line . it prints <td>$row[$key]</td> not the result you are fetching from DB.
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
$i = 1;
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
if($i == 1 || $i ==3){
echo "<th><a href='".key ."'" . $key . "</a></th>";
}else{
echo "<th>" . $key . "</th>";
}
$i++;
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
$j =1;
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
if($i == 1 || $i ==3){
echo "<td><a href='".$row[$key]."'".$row[$key]."</a></td>";
}else{
echo "<td>$row[$key]</td>";
}
}
echo "</tr>";
}
echo "</table>";

Convert array to another array

I have one array that I am showing like this:
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
The second and fourth columns are always the name of the column. The result is something like:
Name: John Locke - NickName: Locke
Age: 20 - Adress: Ok
See the pattern?
How can I put these array in my database?
As my database table structure is:
ID - Name - NickName - Age - Adress
I don't have a clue how to do that with the array i'm using..
--UPDATE
$table = $html->find('table', 0);
$rowData = array();
foreach($table->find('tr') as $row) {
// initialize array to store the cell data from each row
$flight = array();
foreach($row->find('td') as $cell) {
foreach($cell->find('span') as $e){
$e->innertext = '';
}
// push the cell's text to the array
$flight[] = $cell->plaintext;
}
$rowData[] = $flight;
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
echo '<td>' . $row . '</td>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
you can do that:
$insert = "";
foreach ($rowData as $row => $tr) {
$insert .= "('".$tr[0]."','".$tr[0]."','".$tr[0]."','".$tr[0]."'),";
}
$insert = substr($insert, 0, -1)
$sql = "Insert into YourTable values ".$insert;
As you already know what the array positions relate to, IE positions 0 through 3. You can simply iterate as you are doing now and compile a query instead.
Just drop this snippet into your code, ive knocked this up on the fly and its a bit hackish, probably a better way. Just look at what it does on your screen and see where if any it needs correcting.
$insert = '';
for ($i=0; $i<=3; $i++):
$insert .= "'" . $tr[$i] . "'";
if ($i !== 3):
$insert .= ',';
endif;
endfor;
echo $insert;
Once you are seeing what looks like a correct insert then you can (using safe methods) insert it into your database.

Populate an html table columwise with mysql data

I have a MySQL query that returns data using PHP.
My problem is that I need to populate my html table (with 3 columns) with the data returned by the query but the data should be populated Columnwise.
Like first the first column should be populated .. then the second and finally the third one.
Also I would like to know that is it possible to do so for an unlimited set of data?
Following the screen shot of the desired layout
you can use while.
<table>
$sql=mysql_query("select * from table");
while($s=mysql_fetch_array($sql))
{
$x=$s["x"];
<tr>
<td ><?php echo $x; ?></td>
<td ><?php echo $y; ?></td>
<td ><?php echo $z; ?></td>
</tr>
}
</table>
guybennet's answer is correct but if you want it to work for an unlimited amount of columns you could do this: (I also threw in some column headers for readability)
echo '<table>';
$counter = 0;
$result = mysql_query("select * from table");
while($row = mysql_fetch_array($result)) {
$counter++;
if($counter == 1) {
echo '<tr>';
foreach($row as $key => $val) {
echo "<th>$key</th>";
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
echo '</table>';
Also of course you should use mysqli or PDO I'm just showing a quick example.
If you don't care about how it's organized, you can try something like this:
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($sql))
{
echo "<td>".$row[0]."</td>\n";
$i++;
if($i==3)
{
echo "</tr>\n<tr>";
$i=0;
}
}
echo "</tr></table>";
Otherwise, I'd suggest putting it all into an array and then putting it into the table.
$data = array();
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
$itemsAmount = count($data);
$ceilAmount = ($itemsAmount - $itemsAmount % 3) / 3;
$lastAmount = $itemsAmount % 3;
$firstArray = array_slice($data, 0, $itemsAmount);
$secondArray = array_slice($data, 0, $itemsAmount*2);
$thirdArray = array_slice($data, 0, $lastAmount);
$output = "<table>";
foreach ($data as $key => $value) {
$output .= "<tr>";
$output .= "<td>" . $firstArray[$key][0] . "</td>";
$output .= "<td>" . $secondArray[$key][0] . "</td>";
if (empty($thirdArray[$key])) {
$str = '';
} else {
$str = $thirdArray[$key][0];
}
$output .= "<td>" . $str . "</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
You need to check all the results returned, then print them as you won't print in order:
First get an array with all the results
<?php
$sql= mysql_query('SELECT * FROM table');
$num= mysql_affected_rows($sql);
$items = array();
$i=0;
while($item=mysql_fetch_array($sql)){
$items[++$i]=$item['data'];
}
Now start printing
int $num_rows;
$num_rows=$num%3;
echo '<table>';
for ($i=0;$i<$num_rows;$i++){
echo '<tr>';
for ($j=0;$j<2,$j++){
$n=$i+1+($j*$num_rows);
if($items[$n]!==null)
echo '<td>'.$items[$n].'</td>';
else
echo '<td></td>';
}echo '</tr>';
}echo'</table>';
?>

Categories