How to Create a HTML Table from a PHP Array

PHP output array as an HTML table

Try something like this:

$data = //your array
$html = "<table>";
foreach($data as $row) {
$html .= "<tr>";
foreach ($row as $cell) {
$html .= "<td>" . $cell . "</td>";
}
$html .= "</tr>";
}
$html .= "</table>";

Your question is extremenly vague so this is a vague answer, but you should get the general idea :P

How to populate an html table with data from an array in php

You have several problems.

  1. Array indexes start at 0, not 1. But it's usually clearer to use foreach.
  2. You shouldn't hard-code the array lengths, use count().
  3. You're missing several $ before variable names.
  4. You're not printing the times from $times. They should be printed as a header line before the first day.
  5. You shouldn't have $i = $i + 1;, as you'll increment $i twice because of $i++.
$days = array('Monday', 'Tuesday', 'Wednesday', 'Thurstday', 'Friday');
$times = array('08:00-08:45','09:00-09:45','10:05-10:50','11:05-11:50','12:05-12:50','13:20-14:05','14:20-15:05');
$columns = count($times);

echo "<table border='1'>";
echo "<tr><th>Day</th>;";
foreach ($times as $time) {
echo "<th>$time</th>";
}
echo "</tr>";
foreach ($days as $day) {
echo("<tr><th>$day</th>");
for ($i = 0; $i < $columns; $i++) {
echo "<td></td>"; // empty fields for each period
}
}
echo "</tr>";
echo("</table>");

Create html table from arrays

Try this, which uses the php in_array() function.

<table>
<tr>
<?php
// header
foreach ($tb_headers as $value) echo '<th>' . $value . '</th>';
?>
</tr>
<?php
// content
foreach ($tb_data as $line => $values) {
echo '<tr>';
foreach ($tb_headers as $header) {
echo '<td>';
if (in_array($header, $values)) echo $header;
else echo '-';
echo '</td>';
}
echo '</tr>';
}
?>
</table>

Creating HTML Table with PHP Array

Here is a way to do it.

<html>
<body>
<table>
<tr id="subject"><?php
$subjects = array("IT","Programming","Networks");
foreach($subjects as $key => $value) {
echo "<td>"."<a href='index.php' class='column'>".$value."</a>"."</td>";
}
?></tr>
</table>
</body>


<script type="text/javascript">

var elems = document.getElementsByClassName('column');
for (var i = 0; i < elems.length; i++) {
elems[i].onclick = function () {
console.log(this.innerHTML);
};
}

</script>

Notice I added a column class to links, and I'm checking if users click on columns.

Edit: This is assuming I understood your question correctly. Otherwise if your actual code prints multiple rows, with multiple links, and you're trying to get the value of a row, then you shouldn't have multiple ids in your html. id is unique, class is for elements that repeat.



Related Topics



Leave a reply



Submit