PHP table rows based on table header - php

i want to create a table of all classes as table header and rows with name of student in each class each column according to it header, all data come from two (students, classes) mx code :
<table>
<thead >
<?php
foreach ($groupList as $group):
?>
<th><?= $group['group_name'] ?></th>
<?php endforeach; ?>
</thead>
<tbody>
<tr>
<?php
foreach ($groupList as $group) {
echo '<td>' ;
foreach ($db->getStudentsByGroup($group['u_id']) as $name){
echo $name['fname'] ;
}
echo '</td>';
}
?>
</tr>
</tbody>
this code shows them grouped as wanted but all names are in the same row as below
group1 group2
tom, sam, bob, x, y ,...
mark, ...
, i tried to change the location of the (td, tr) but no success, any idea how to do it properly , thanks in advance

If i m not wrong this should do the trick!
my array:
$array = array(
'group1' => array(
'aaa',
'bbb',
'ccc'
),
'group2' => array(
'ddd',
'eee',
'fff'
)
);
Working code:
echo '
<table border="1">
<thead>';
foreach($array AS $tname => $tvalue){
echo '<th>'.$tname.'</th>';
}
echo '
</thead>
<tbody>';
$keys = array_keys($array);
$first_key = $keys[0];
foreach ($array[$first_key] as $id => $value) {
$body .= "<tr>";
foreach ($keys as $k) {
$body .= "<td>" . $array[$k][$id] . "</td>";
}
$body .= "</tr>";
}
echo $body;
echo '
</tbody>
</table>';

Related

How to turn a table vertical using PHP

I am just learning PHP ,and I want to create a table that display echo data that I submit to my database , the problem I have that the table displayed horizontally by default as you see Horizontal default table this my script
<table >
<tr>
<th>Name</th>
<th>Age</th>
<th>Height</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Age"] . "</td><td>"
. $row["Height"]. "</td></tr>";
}
echo "</table>";
} else //{ echo "0 results"; }//
$conn->close();
?>
</table>
but I want it to be echoed vertically instead like this VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can't get the result at all and the shape of the table is far away from what I want and this is the full script of my page .
Like everyone else said, you should convert your horizontal array into a vertical one.
Of course it should be a universal function to convert any query result, as opposed to hardcoding the row headings. The idea is to get each row's array keys and use them as the keys for the new array and then add each corresponding value to the new array item.
Here is how it's done in mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('127.0.0.1','root','','test');
$mysqli->query("set names 'UTF8'");
$data = [];
$res = $mysqli->query("SELECT Name, Age, Height FROM student order by Name desc");
while ($row = $res->fetch_assoc()) {
foreach(array_keys($row) as $key) {
$data[$key][] = $row[$key];
}
}
and then you get an array with desired structure which you can output using the code from ROOT's answer:
<table border="1">
<?php foreach($data as $key => $val): ?>
<tr>
<td><?= $key ?></td>
<?php foreach($val as $field): ?>
<td><?= $field ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
I mocked your data into normal array, I used a while loop to create a new Array and create the format that we need to be able to flip the columns into rows, here is what I think you want:
<?php
$users = [
[
'name'=> 'James',
'height'=> 1.75,
'age'=> 18,
],
[
'name'=> 'Bill',
'height'=> 170,
'age'=> 16,
]
];
$newArr = [];
foreach($users as $key => $val) {
$newArr['name'][$i] = $val['name'];
$newArr['age'][$i] = $val['age'];
$newArr['height'][$i] = $val['height'];
$i++;
}
?>
<table border="1">
<?php foreach($newArr as $key => $val): ?>
<tr>
<td><?php echo $key; ?></td>
<?php foreach($val as $field): ?>
<td><?php echo $field; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach ?>
</table>
It's not a good idea ! if you have a lot of ROW you will generate a long table not visible for user in screen.
if you want to do it after all you can change table structure but you will not respect html table structure.
I will give you a
Dirty code
<table>
<tr>
<th>Name</th>
<?php foreach ($row as $value) { ?><td><?php echo$value["Name"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Age</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Age"]; ?></td>
<?php } ?>
</tr>
<tr>
<th>Height</th>
<?php foreach ($row as $value) { ?>
<td><?php echo $value["Height"]; ?></td>
<?php } ?>
</tr>
</table>
I recommand to USE CSS instead a table

html table and populate with php with empty rows

I am trying to fill table with data.
I want to achieve something that looks like
However, my result is:
I guess this might be related to the php IF-statement.
Here is my code:
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="2" rowspan="4">OPPONENT</th>
<th class="tg-s6z2" colspan="5">DIVISION</th>
</tr>
<tr>
<td class="tg-s6z2" colspan="5">TEAM</td>
</tr>
<tr>
<?php
foreach($rows as $row) {
echo "<td class='tg-031e' colspan='2'>";
echo $row["Date"];
echo "</td>";
}
?>
</tr>
<tr>
</tr>
<?php
foreach($rows as $row) {
echo"<tr>";
echo "<td class='tg-031e' colspan='2'>";
echo $row["teamName"];
echo "</td>";
if(!empty($row["Score"])){
echo"<td>";
echo$row["Score"];
echo "</td>";
}else{
echo "<td> </td>";
}
echo"</tr>";
}
?>
</table>
THE OUTPUT OF $results
Array (
[0] => Array (
[Date] => 2015-04-22
[0] => 2015-04-22
[Score] => 1:4
[1] => 1:4
[divisionID] => 2
[2] => 2
[3] => 2
[teamName] => TEAM YXZ
[4] => TEAM XYZ )
[1] => Array (
[Date] => 2015-04-15
[0] => 2015-04-15
[Score] => 2.5:2.5
[1] => 2.5:2.5
[divisionID] => 2
[2] => 2
[3] => 2
[teamName] => TEAM XYZ 'B'
[4] => TEAM XYZ 'B'
)
)
You need to loop over the dates of the column headings, checking whether the current element of $rows matches the corresponding date. First make an array of all the dates when you're creating the headings:
$dates = array();
foreach($rows as $row) {
echo "<td class='tg-031e' colspan='2'>";
echo $row["Date"];
$dates[] = $row['Date'];
echo "</td>";
}
Then when you write the rows, loop through the dates. When it matches, write the score, otherwise leave the <td> empty (there's no need to write ).
foreach($rows as $row) {
echo"<tr>";
echo "<td class='tg-031e' colspan='2'>";
echo $row["teamName"];
echo "</td>";
foreach ($dates as $date) {
echo "<td>";
if ($row['Date'] == $date && !empty($row['Score'])) {
echo $row["Score"];
}
echo "</td>";
}
echo"</tr>";
}
Your conditional statement checking $row['score'] is saying add a TD with a score or add a TD with nothing. You still need to add a TD regardless if it's blank or not or it will break the table layout.
Also, the data you get back, is it enough data for the loop to fill out the whole table? It seems to me that there is something going on with the data being returned along with the conditional statement.
The example image you gave is not corresponding with the data $rows has. The match on 2015-04-22 should have the score 1:4 right?
I've separated the logic from the HTML.
In my opinion, the way $rows is constructed is generally bad design.
With that in mind; here's what I've came up with;
<?php
$dates = array();
foreach ($rows as $row):
$dates[] = $row['Date'];
endforeach;
$matches = array();
foreach ($rows as $row):
$scores = array();
foreach ($dates as $date):
$score = '';
if (!empty($row['Score']) && $row['Date'] === $date):
$score = $row['Score'];
endif;
$scores[] = $score;
endforeach;
$matches[] = array('teamName' => $row['teamName'], 'Scores' => $scores);
endforeach;
?>
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="2" rowspan="4">OPPONENT</th>
<th class="tg-s6z2" colspan="5">DIVISION</th>
</tr>
<tr>
<td class="tg-s6z2" colspan="5">TEAM</td>
</tr>
<tr>
<?php foreach ($dates as $date): ?>
<td>
<?php echo $date; ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
</tr>
<?php foreach ($matches as $match): ?>
<tr>
<td class="tg-031e" colspan="2">
<?php echo $match['teamName']; ?>
</td>
<?php foreach ($match['Scores'] as $score): ?>
<td><?php echo $score; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

PHP Foreach array to table display

I have an array $day and want to display this array in table form (I'm working with CI)
Array (
[START_EXECUTION] =>
Array (
[0] => 27-OCT-14
[1] => 28-OCT-14
[2] => 29-OCT-14
)
[NUM_OF_POPULATION] =>
Array (
[0] => 6171
[1] => 6990
[2] => 6882
)
[SUM_AMOUNT] =>
Array (
[0] => 361154716.01
[1] => 409210099.77
[2] => 407191552.71
)
)
Here is my code that I use in view :
<?php
if(count($day)>0){
print_r($day);
foreach($day as $index => $dt1_element){
?>
<table class='table'>
<tr>
<td><?= $index ?></td>
</tr>
<?php
foreach($dt1_element as $row){
?>
</tr>
<td><?= $row ?></td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
<?php
}
?
But what I get is like this :
START_EXECUTION
27-OCT-14
28-OCT-14
29-OCT-14
NUM_OF_POPULATION
6171
6990
6882
SUM_AMOUNT
361154716.01
409210099.77
407191552.71
The result should be :
START_EXECUTION NUM_OF_POPULATION SUM_AMOUNT
27-OCT-14 6171 361154716.01
28-OCT-14 6990 409210099.77
29-OCT-14 6882 407191552.71
Kindly show me the correct foreach to get the desired result. Thank you
Try this:
echo '<table>';
$cols = array_keys($day);
echo '<tr>';
foreach ($cols as $col) echo '<th>' . $col . '</th>';
echo '</tr>';
foreach ($day[$cols[0]] as $i => $null) {
echo '<tr>';
foreach ($cols as $col) echo '<td>' . $day[$col][$i] . '</td>';
echo '</tr>';
}
echo '</table>';
demo
You are unnecessarily closing <tr>.
All you need is the child amounts on a separate row.
Corrected code:
<?php
if(count($day)>0){
print_r($day);
foreach($day as $index => $dt1_element){
?>
<table class='table'>
<tr>
<td><?php echo $index;?></td>
</tr>
<?php
$tds = array();
foreach($dt1_element as $row){
$tds[] = '<td>'.$row.'</td>';
?>
<?php
}
echo "<tr>". impldoe(' ', $tds) ."</tr>";
?>
<?php
}
?>
</table>
<?php
}
?>
if you use PHP>=5.5 than
echo "<table>";
$cols = array_keys($day);
echo "<tr><th>";
echo implode('</th><th>', $cols);
echo "</th></tr>";
for ($i = 0, $num = count($cols); $i < $num; ++$i)
{
echo "<tr><td>";
echo implode('</td><td>', array_column($day, $i));
echo "</td></tr>";
}
echo "</table>";
Here works fine
print "<table><tr><th>START_EXECUTION |</th><th>NUM_OF_POPULATION |</th><th>SUM_AMOUNT |</th></tr>";
//$index=0;
foreach($vals['START_EXECUTION'] as $index=>$values){
echo "<tr><td>$values</td><td>".$vals['NUM_OF_POPULATION'][$index]."</td><td>".$vals['SUM_AMOUNT'][$index]."</td></tr>";
//$index++;
} print '</table>';
for demo here
My response is inspired by the "Two-Step View" pattern where I build the logical data for the view to avoid any unnecessary information being in the view (for example, I'm not a fan of having array indices in views if I can help it):
<?php
$arr = array(
'START_EXECUTION'=>array(
'27-OCT-14',
'28-OCT-14',
'29-OCT-14',
),
'NUM_OF_POPULATION'=>array(
6171,
6990,
6882,
),
'SUM_AMOUNT'=>array(
361154716.01,
409210099.77,
407191552.71,
),
);
$headers = array_keys($arr);
$body = array_map(function($a, $b, $c) { return array($a, $b, $c); },
$arr['START_EXECUTION'],
$arr['NUM_OF_POPULATION'],
$arr['SUM_AMOUNT']
);
$table = array(
'headers'=>$headers,
'body'=>$body,
);
?>
$table will contain the logical structure of the table in a view independent way.
We can create a simple widget that will convert the logical data into a html table like so:
<table class="table">
<thead>
<tr>
<?php foreach($table['headers'] as $header): ?>
<th><?php echo $header; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($table['body'] as $row): ?>
<tr>
<?php foreach ($row as $col): ?>
<td><?php echo $col; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
As long as you maintain the same logical structure, the html code snippet can be placed inside a "widget" and that's the beginning of a table renderer.
Note This is just meant as a prototype and is not intended to be a comprehensive solution.
$data = array($FIELDS);//field value like name,email,password etc.
foreach($data as $row)
{
echo "<tr>";
foreach($row as $column){
echo "<th>".$column."</th>";
}
echo "</tr>";
}
you can create array of field and add field data in array try this ...

PHP - seperate array based on characters in key

I have a PHP array from a submitted form that looks like the following
$form_data = Array (
[input_1_1] => Product Name
[input_1_2] => $8.00
[input_1_3] => 2
[input_2_1] => Other Product Name
[input_2_2] => $3.50
[input_2_3] => 8
)
I am looking for the best way to parse this so I can build something markup like this:
<table>
<tr>
<td>Product Name</td>
<td>$8.00</td>
<td>2</td>
</tr>
<tr>
<td>Other Product Name</td>
<td>$3.50</td>
<td>8</td>
</tr>
</table>
What would be most kosher way to do this?
Should I split this array into smaller arrays based on the 1st number (and then loop them)?
Alternatively should I just build the markup based on sets of three, like:
<table>
<tr>
<td><?php echo $form_data[1]; ?></td>
<td><?php echo $form_data[2]; ?></td>
<td><?php echo $form_data[3]; ?></td>
</tr>
<tr>
<td><?php echo $form_data[4]; ?></td>
<td><?php echo $form_data[5]; ?></td>
<td><?php echo $form_data[6]; ?></td>
</tr>
</table>
Any help/advice appreciated.
take a look on this example: http://codepad.org/zhKbc4p1
$arr = array('input_1_1'=>'Name', 'input_1_2'=>'$8', 'input_1_3'=>1, 'input_2_1'=>'Name', 'input_2_2'=>'$28', 'input_2_3'=>1);
$chunk = array_chunk($arr, 3);
print_r($chunk);
foreach( $chunk as $val ){
foreach($val as $v){
echo $v . "\r\n";
}
echo "\r\n\r\n";
}
Expected HTML format:
foreach( $chunk as $val ){
echo "<tr>";
foreach($val as $v){
echo "<td>" . $v . "</td>";
}
echo "</tr>";
}
$last_group = '';
foreach ($form_data as $key => $value) {
preg_match('/input_(\d+)/', $key, $match);
if ($match[1] != $last_group) {
if ($last_group) {
echo "</tr>\n";
}
echo "<tr>\n";
$last_group = $match[1];
}
echo "<td>$value</td>\n";
}
if ($last_group) {
echo "</tr>\n";
}
It would be better to structure your form like this, though:
<input type="text" name="name[]">
<input type="text" name="price[]">
<input type="text" name="quantity[]">
Then the $_POST['name'], $_POST['price'] and $_POST['quantity'] will be arrays, and you can iterate over them:
foreach ($_POST['name'] AS $i => $name) {
$price = $_POST['price'][$i];
$quantity = $_POST['quantity'][$i];
// Output the table row
}
Assuming each table row has 3 elements each;
<?php
echo "<table>
<tr>";
$form_data = Array (
"input_1_1" => "Product Name",
"input_1_2" => "$8.00",
"input_1_3" => "2",
"input_2_1" => "Other Product Name",
"input_2_2" => "$3.50",
"input_2_3" => "8"
);
$intRowBefore = 1;
foreach( $form_data as $strKey => $strVal ) {
$intRow = explode("_", $strKey)[1];
if( $intRowBefore != $intRow ) {
echo "</tr><tr>";
$intRowBefore = $intRow;
}
echo "<td>". $strVal ."</td>";
}
echo "</tr></table>";
Consider
<?php
$form_data = array();
$form_data['input_1_1'] = 'Product Name';
$form_data['input_1_2'] = '$8.00';
$form_data['input_1_3'] = '2';
$form_data['input_2_1'] = 'Other Product Name';
$form_data['input_2_2'] = '$3.50';
$form_data['input_2_3'] = '8';
// Get unique keys
function get_unique_keys($keys)
{
$arr = array();
foreach($keys as $k=>$v){
$arr[] = substr($k, 0, strlen($k)-2);
}
return array_unique($arr);
}
$keys = get_unique_keys($form_data);
// Output
printf("<table>\n");
foreach($keys as $k)
{
printf(" <tr>\n");
printf(" <td>%s</td>\n", $form_data[$k.'_1']);
printf(" <td>%s</td>\n", $form_data[$k.'_2']);
printf(" <td>%s</td>\n", $form_data[$k.'_2']);
printf(" </td>\n");
}
printf("</table>\n");
Which outputs:
<table>
<tr>
<td>Product Name</td>
<td>$8.00</td>
<td>$8.00</td>
</td>
<tr>
<td>Other Product Name</td>
<td>$3.50</td>
<td>$3.50</td>
</td>
</table>
See it in action: http://ideone.com/355STr
It's not super complicated. It gets the key "roots" we'll call them (input_1, input_2, etc) and loops over those, appending the additional _1,_2,_3 when needed.
A better solution long-term would be to redesign the form, but that's not always a possibility.
Try This
$form_data = Array (
'[input_1_1]' => 'Product Name',
'[input_1_2]' => '$8.00',
'[input_1_3]' => '2',
'[input_2_1]' => 'Other Product Name',
'[input_2_2]' => '$3.50',
'[input_2_3]' => '8'
);
echo "<table>";
foreach($form_data as $k=>$v)
{
echo "<tr>";
echo "<td>".$v."&lt/td>";
echo "</tr>";
}
echo "</table>";
<?php
$form_data = array(
'input_1_1' => 'Product Name',
'input_1_2' => 8.00,
'input_1_3' => 2,
'input_2_1' => 'Other Product Name',
'input_2_2' => 3.50,
'input_2_3' => 8
);
end($form_data);
$counter = explode('_',key($form_data));
?>
<table>
<?php
$i = 1;
$j = 1;
for ($k = 1; $k <= $counter[1]; $k++) {
?>
<tr>
<td><?php echo $form_data['input_' . $j . '_' . $i]; ?></td>
<td><?php $i++;echo $form_data['input_' . $j . '_' . $i]; ?></td>
<td><?php $i++;echo $form_data['input_' . $j . '_' . $i]; ?></td>
</tr>
<?php
if ($i == 3) {
$i = 1;
$j++;
}
}
?>
</table>

How to change an array into a html table in sample way?

I have a dynamic array :
Array
(
[user1] => Array
(
[012014] => 6788
[022014] => 11141
[032014] => 6143
[042014] => 936
[052014] => 936
)
[user2] => Array
(
[012014] => 9
[022014] => 25
[032014] => 37
[042014] => 17
[052014] => 16
)
)
And I want to display it like this :
Users | Months
|---------------------------------
|012014|022014|032014|042014|052014
------------------------------------------
user1 | 6788 | 11141| 6143 | 936 | 936
-------------------------------------------
user2 | 9 | 25 | 37 | 17 | 16
I can't seem to work it out! Here's what I've been trying :
echo "<table>";
foreach($month_all as $site=>$value){
echo "<tr>";
echo "<td>$site</td>";
foreach ($value as $column) {
echo "<td>$column</td>";
}
echo "</tr>";
}
echo "</table>";
Any way I can do it in a clean way ?
Use two loops: one for displaying all the key values. One for displaying all the values of the users. This version uses <th> to handle the table headers and takes care of the indentation properly because it's using the alternative foreach style.
<table>
<tr>
<th>User</th>
<th colspan="5">Months</th>
<tr>
<th></th>
<?php foreach ($month_all['user1'] as $key): ?>
<td><?= $key ?></td>
<?php endforeach ?>
</tr>
</tr>
<?php foreach ($month_all as $site => $value): ?>
<tr>
<td><?= $site ?></td>
<?php foreach ($value as $column): ?>
<td><?= $column ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
Live demo
you can use like this
<table>
<tr>
<?php
foreach($Arr['user1'] as $key1=>$th)
{
?>
<th><?=$key1?></th>
<?php
}
?>
</tr>
<?php
foreach($Arr as $row)
{ ?>
<tr>
<?php
foreach($row as $column){
?>
<td><?=$column?></td>
<?php } ?>
</tr>
<?php}
?>
</table>
Clearly speaking using implode is not a good method to use.But i wanted to give you an idea that you should use colspan='.count(array_keys($month_all['user1'])).' in header to get month over all columns.
echo '<table><tr><td rowspan=2>Users</td><td colspan='.count(array_keys($month_all['user1'])).'>Months</td></tr>';
echo '<td>'.rtrim(implode(array_keys($month_all['user1']),'</td><td>'),'<td>').'';
foreach($month_all as $site=>$value){
echo "<tr>";
echo "<td>$site</td>";
foreach ($value as $column) {
echo "<td>$column</td>";
}
echo "</tr>";
}
This will give u the exact table as in your question
<?php
$array = array(
"user1" => array(
"012014" => 6788,
"022014" => 11141,
"032014" => 6143,
"042014" => 936,
"052014" => 936
) ,
"user2" => array(
"012014" => 9,
"022014" => 25,
"032014" => 37,
"042014" => 17,
"052014" => 16
)
);
print '<table border="1px solid black"><tr><td>Users</td><td colspan="5" style="text-align: center">Month</td></tr>';
print '<tr><td></td>';
foreach (reset($array) as $key => $value) {
print '<td>' . $key . '</td>';
}
print '</tr>';
foreach ($array as $key => $values) {
print '<tr>';
print '<td>' . $key . '</td>';
foreach ($values as $value) {
print '<td>' . $value . '</td>';
}
print '</tr>';
}
print '</table>';
?>
result:

Categories