Displaying an array of data in to a table of 4 columns - php

I have a php array which contains 45 items that I would displayed into a table of 4 columns. The code below is what I have.
$output = '<table border="1">';
for($tr=0; $tr<=count($question_answers); $tr++)
{
$output .= "<tr>";
for($td=1; $td<=$cols; $td++){
$output .= "<td>" . $question_answers[$tr] . "</td>";
}
$output .= "</tr>";
}
$output .= "</table>";
How do I split that data so that it split into 4 columns? Any ideas?

$output = '<table border="1">';
for($tr=0; $tr<=count($question_answers); $tr++)
{
$output .= "<tr>";
for($td=1; $td<=$cols; $td++){
$output .= "<td>" . $question_answers[$tr] . "</td>".($tr % 4 == 0 ? "</tr><tr>" : "");
}
$output .= "</tr>";
}
$output .= "</table>";
Or for this case: "What I am trying to achieve a table with a maximum of 12 rows and 4 columns. The first column would be from 1 to 12, second column 13 - 24, third column 25 - 36 and fourth column 37 etc... "
$output = '<table border="1">';
for($tr=0; $tr<12; $tr++){
$output .= "<tr>";
for($td=0; $td<=3; $td++){
if(!empty($question_answers[$td*12+$tr]))
$output .= "<td>" .$question_answers[$td*12+$tr] . "</td>";
}
$output .= "</tr>";
}
$output .= "</table>";
The result would be:
http://joxi.ru/E2pbzzvf8Xp8rY

Related

How to loop a JSON nested Array into table list

Hi I am trying to read a nested JSON array data into a table and as a list not just in a line.
Look, at the way it comes out:
Link to JSON: JSON
L: demo
P: ocfB6XzF73
Documentation: URL-DOC
JSON code I am trying to reach:
"EquipmentList": [ "ABSBrakes", "Alarm", "AlloyRims", "AntiSpin", "AutomaticGear", "RemoteCentralLocking", "PoweredWindows", "PoweredMirrorsHeated", "CruiseControl", "InfoCenter", "AutomaticClimateControl", "TripComputer", "Navigation", "GearShiftStearingWheel", "ServiceOK", "Immobilizer", "SeatHeater", "XenonLight" ]
My code so far i very simple as I struggle to list the data to a list i.e. LI or a TABLE :
<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';
// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");
// create HTTP context with basic auth
$context = stream_context_create([
'http' => ['header' => "Authorization: Basic $auth"]
]);
// query for data
$data = file_get_contents($url, false, $context);
// $escaped = json_encode($data);
$escaped = json_decode($data); //, JSON_FORCE_OBJECT
/*Initializing temp variable to design table dynamically*/
$temp = "<table>";
/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr>";
$temp .= "<th>Bil</th>";
$temp .= "<th>Model</th>";
$temp .= "<th>Motor</th>";
$temp .= "<th>Drivmiddel</th>";
$temp .= "<th>Udstyr</th>";
$temp .= "<th>Billeder</th>";
$temp .= "</tr>";
/*Dynamically generating rows & columns*/
foreach ($escaped->Vehicles as $vehicle) {
$temp .= "<tr>";
$temp .= "<td>" . $vehicle->Make . "</td>";
$temp .= "<td>" . $vehicle->Model . "</td>";
$temp .= "<td>" . $vehicle->Motor . "</td>";
$temp .= "<td>" . $vehicle->Propellant . "</td>";
foreach($escaped->Vehicles[0]->EquipmentList as $EquipmentItem){
$temp .= "<td>" . $EquipmentItem . "</td>";
}
for ($p = 0; $p < $vehicle->PictureCount; $p++) {
$temp .= "<td><img src='" . $vehicle->Pictures[0] . "'></td>";
}
}
$temp .= "</tr>";
/*End tag of table*/
$temp .= "</table>";
/*Printing temp variable which holds table*/
echo $temp;
echo $data;
?>
With the help of Anand Pandey
<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';
// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");
// create HTTP context with basic auth
$context = stream_context_create([
'http' => ['header' => "Authorization: Basic $auth"]
]);
// query for data
$data = file_get_contents($url, false, $context);
// $escaped = json_encode($data);
$escaped = json_decode($data); //, JSON_FORCE_OBJECT
/*Initializing temp variable to design table dynamically*/
$temp = "<table class='car-list'>";
/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr>";
$temp .= "<th class='th-style'>Bil</th>";
$temp .= "<th class='th-style'>Model</th>";
$temp .= "<th class='th-style'>Motor</th>";
$temp .= "<th class='th-style'>Drivmiddel</th>";
$temp .= "<th class='th-style'>Udstyr</th>";
$temp .= "<th class='th-style'>Billeder</th>";
$temp .= "</tr>";
/*Dynamically generating rows & columns*/
foreach ($escaped->Vehicles as $vehicle) {
$temp .= "<tr>";
$temp .= "<td class='td-style'>" . $vehicle->Make . "</td>";
$temp .= "<td class='td-style'>" . $vehicle->Model . "</td>";
$temp .= "<td class='td-style'>" . $vehicle->Motor . "</td>";
$temp .= "<td class='td-style'>" . $vehicle->Propellant . "</td>";
$temp .= "<td class='td-style'>";
foreach ($escaped->Vehicles[0]->EquipmentList as $EquipmentItem) {
$temp .= "<table>";
$temp .= "<tr>";
$temp .= "<td class='equipmentlist'>" . $EquipmentItem . "</td>";
$temp .= "</tr>";
$temp .= "</table>";
}
$temp .= "</td>";
$temp .= "<td class='td-style'>";
for ($p = 0; $p < $vehicle->PictureCount; $p++) {
$temp .= "<table>";
$temp .= "<tr>";
$temp .= "<td class='td-style'>";
$temp .= "<img class='cc-images' src='" . $vehicle->Pictures[$p] . "'>";
$temp .= "</td>";
$temp .= "</tr>";
$temp .= "</table>";
}
$temp .= "</td>";
}
$temp .= "</tr>";
/*End tag of table*/
$temp .= "</table>";
/*Printing temp variable which holds table*/
echo $temp;
//echo $data;
?>

How to parse data returned from a text file into an HTML table using PHP

I am returning book data (title, ISBN, author) information from a text file into an array. I am able to pull the data from the text file, read it it and display it as an array but how do I display this information into an HTML table? The HTML table needs to be created using PHP. Where I print the $book in the foreach, all the books are returned as an array but How do I output them in an HTML table created using solely php. I am NOT receiving errors, just need to know how to insert the return the data into an HTML table using PHP.
? Here is what I have so far
PHP
<?php
$infoArray = array(); //New empty array
$filename = 'books.txt';
$lines = count(file($filename));
$fp = fopen($filename, 'r');
for($ii = 1; $ii <= $lines; $ii++){
$line = fgets($fp);
array_push($infoArray, $line);
}
fclose($fp);
sort($infoArray);
list($title, $ISBN, $Author) = explode('*', $line);
$cntr = 0;
foreach ($dataReturned as $line){
print $line;
print '<br>';
}
This is what I want to print out as but it is not working. I am unsure how and where to incorporate this code.
$htmltable = "<table border='1'>";
$htmltable .= "<tr>";
$htmltable .= "<th>Title</th>";
$htmltable .= "<th>ISBN</th>";
$htmltable .= "<th>Author</th>";
$htmltable .= "</tr>";
$htmltable .= "<tr $style>";
$htmltable .= "<td>".$title."</td>";
$htmltable .= "<td>".$ISBN."</td>";
$htmltable .= "<td>".$Author."</td>";
$htmltable .= "</tr>\n";
print $htmltable;
TEXT FILE INFO
These are a few lines being pulled from the text file.
Healthy Living*1-4988-9986-x*Smith
How to Live Life*1-5698-9865-x*Romero
Better Speech*1-6996-9989-x*Grimes
This is one possible approach:
PHP:
<?php
#
$filename = 'file-books.txt';
$file = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
#
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>ISBN</th>";
echo "<th>Author</th>";
echo "</tr>";
echo "</thead>";
# Extract the lines.
echo "<tbody>";
foreach ($file as $row) {
$fields = explode('*', $row);
echo "<tr>";
echo "<td>".$fields[0]."</td>";
echo "<td>".$fields[1]."</td>";
echo "<td>".$fields[2]."</td>";
echo "</tr>";
}
#
echo "</tbody>";
echo "</table>";
?>
Text file:
Healthy Living*1-4988-9986-x*Smith
How to Live Life*1-5698-9865-x*Romero
Better Speech*1-6996-9989-x*Grimes
Just reading the file as a CSV (although with a * delimeter)...
$fp = fopen($filename, 'r');
$style = "";
$htmltable = "<table border='1'>";
$htmltable .= "<tr>";
$htmltable .= "<th>Title</th>";
$htmltable .= "<th>ISBN</th>";
$htmltable .= "<th>Author</th>";
$htmltable .= "</tr>";
while ( $row = fgetcsv($fp, null, "*")) {
$htmltable .= "<tr $style>";
$htmltable .= "<td>".$row[0]."</td>";
$htmltable .= "<td>".$row[1]."</td>";
$htmltable .= "<td>".$row[2]."</td>";
$htmltable .= "</tr>\n";
}
$htmltable .= "</table>\n";
fclose($fp);
echo $htmltable;
$html_table = '';
$html_table .= '<table>';
$html_table .= '<thead>';
$html_table .= '<th>Title</th>';
$html_table .= '<th>ISBN</th>';
$html_table .= '<th>Author</th>';
$html_table .= '</thead>';
$html_table .= '<tbody>';
foreach ($dataReturned as $line){
$html_table .= '<tr>';
$html_table .= "<th>$line[0]</th>";
$html_table .= '<th>$line[1]</th>';
$html_table .= '<th>$line[2]</th>';
$html_table .= '</tr>';
}
$html_table .= '</tbody>';
$html_table .= '</table>';
echo $html_table;
--- Sorry for creating this as new answer, cant edit my last comment with code formatting. ---
Can you show us an example of what data the variable $line contains? Because if its an array, you need to do another foreach inside the "foreach ($dataReturned as $line)" loop to get the data inside the variable $line or if its an object, try to get the respective attribute.
After knowing what you have, try to create an empty variable which is gonna contain all your HTML and use your foreach loop to append the columns and rows.
Are you sure that you have data in the array ? I was checking your code and look good, however you can use "echo" for print data in the browser.
You can test your code in this web page http://phptester.net/-
i hope that it could help you.

PHP While Loops Table Mysqli Results

I'm about month and a half into PHP. I tried to make function for fetching results from find_all_subjects():
function find_all_subjects() {
global $dbconnect;
$q = "SELECT * FROM subjects ORDER BY id ASC";
$subject_set = mysqli_query($dbconnect, $q);
confirm_query($subject_set);
return $subject_set;
}
and then making a new function which will loop the result in table rows. The problem is it loops just one result... when I did it with <ul> and <li> it worked fine but it doesn't seem to work when doing it with the table. My table core tags are in another document. So it's not that...
function navigacija() {
$s = find_all_subjects();
while($subjects = mysqli_fetch_assoc($s)) {
$out = "<tr>";
// Ime Teme
$out .= "<td width='25%' height='40'> <a href=\"admin_content.php?subject=" . urlencode($subjects['id']) . "\">";
$out .= $subjects['menu_name'];
$out .= "</a></td>";
// Vidljiva
if($subjects['visible'] == 1) {
$subjects['visible'] = 'DA';
} else {
$subjects['visible'] = 'NE';
}
$out .= "<td width='25%' height='40'><p align=\"center\">DA / NE";
$out .= "</p></td>";
// Broj Strana
$out .= "<td width='25%' height='40'>";
$pages_set = find_sub_from_pages($subjects['id']);
while($pages = mysqli_fetch_assoc($pages_set)) {
$out .= "" . $pages['menu_name'] . "";
$out .= "</td>";
}
// Vidljiva
$out .= "<td align=\"center\" width='25%' height='40'>";
$out .= "<img width=\"17px\" height=\"17px\" src=\"st/img/ic-arup.png\">
</img> <img width=\"17px\" height=\"17px\" src=\"st/img/ic-ardown.png\"></img> ";
$out .= "</td>";
$out .= "</tr>";
}
return $out;
}
the problem is that you reset
$out = "<tr>";
every time in the loop.
change this line to
$out .= "<tr>";
and only put declaration out of the loop
$out = "";

Display a table in while loop

I am trying to display a table in while loop with 3 rows and 3 td for each row. But I am confusing how to archived thit.
This is my code so far:
while($row = mysqli_fetch_array($result)){
$testimonial = $row['testimonial'];
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
$testimonial = nl2br($testimonial);
//Create new testimonial output
$output = "<table>\n";
$output .= " <tr>\n";
$output .= " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
$output .= " </tr>\n";
$output .= "</table>\n";
echo $output;
}
The above code given me a table with multiple rows and 1 td for each row. But it is not my expecting result.
Can anybody tell me how can I display such a table in my While loop?
The current code creates a new table for every single entry. What you want is to move the <table> and </table> pieces outside of the loop, then you want a counter to keep track of how many cells you've handled. If it's even, start a new <tr>. Otherwise, end the current </tr>. Make sure you check at the end to see if you've finished a </tr>, and optionally add an empty <td></td> if needed.
this aught to do it
<?php
echo "<table>\n";
$cells = $total = 0;
$total_cells = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result))
{
$testimonial = nl2br($row['testimonial']);
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
if ($cells === 0)
echo "<tr>\n";
//Create new testimonial output
$output = " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
echo $output;
$cells++;
$total++;
if ($cells === 3 || $total === $total_cells)
{
echo "</tr>\n";
$cells = 0;
}
}
echo "</table>\n";
?>
Try this
$i = 0;
echo "<table>\n<tr>";
while($row = mysqli_fetch_array($result)){
$testimonial = $row['testimonial'];
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
$testimonial = nl2br($testimonial);
//Create new testimonial output
$output .= " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
echo $output;
if( $i %2 == 1 )
echo "</tr><tr>\n";
$i++;
}
echo "</tr>\n</table>\n";
EDIT
In general, for displaying n cells per row, change the if statement to
if( $i % n == (n - 1) )

display only 3 foreach result per row

i have script as follows
$output="<table class='products'><tr>";
while($info = mysql_fetch_array( $data )) {
//Outputs the image and other data
$output.= "<td>
<img src=http://localhost/zack/sqlphotostore/images/" .$info['photo'] ." width=323px ></img>
<b>Name:</b> ".$info['name'] . "
<b>Email:</b> ".$info['email'] . "
<b>Phone:</b> ".$info['phone'] . "</td> ";
}
$output.="<tr></table>";
print $output;
?>
it shows all results in long horizontal line how do i break the results so that they show
in new row after 3 count.
Keep a counter, and output a new table row every 3 images
$output="<table class='products'>";
$counter = 0;
while($info = mysql_fetch_array( $data ))
{
if( $counter % 3 == 0 )
$output .= '<tr>';
$output .= "<td>";
$output .= "<img src=http://localhost/zack/sqlphotostore/images/".$info['photo'] ." width=323px ></img>";
$output .= "<b>Name:</b> ".$info['name'];
$output .= "<b>Email:</b> ".$info['email'];
$output .= "<b>Phone:</b> ".$info['phone']."</td> ";
if( $counter % 3 == 0)
$output .= "</tr>";
$counter++;
}
$output.="</table>";
print $output;
?>
Add a counter and start a new row every time it reaches a multiple of 3.
$counter = 0;
while($info = mysql_fetch_array($data)) {
if ($counter++ % 3 == 0) {
if ($counter > 0) {
$output .= "</tr>";
}
$output .= "<tr>";
}
// stuff
}
if ($counter > 0) {
$output .= "</tr>";
}
$output .= "</table>";
Please note: It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.

Categories