html table and populate with php with empty rows - php

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>

Related

Move result to the right position on table in PHP

I'm trying to show 7 results on a table (image 1) which I would like to move them to the right position.
Mon = 1 ~ Sun = 7 as we can see on the array and where there is no value I would like to have it $0. At the moment I could not figure out how to move it to the right spot on the table.
Here is my code:
$w_rep = "SELECT
`totals`.`totals_weeknumb`,
`totals`.`totals_weekday`,
`totals`.`totals_of_day`
FROM `totals`
WHERE `totals`.`totals_has_users_id` = :fromID";
$w_rep_stmt = $DB->prepare($w_rep);
$w_rep_stmt->execute(array(':fromID' => $fromID));
$w_rep_stmt->setFetchMode(PDO::FETCH_ASSOC);
$totals_of_day = array();
foreach ($w_rep_stmt as $report) {
//$tdate = new DateTime($report['totals_date']);
//$totals_date = $tdate->format('d-m-Y');
$t_wnumber = (int)$report['totals_weeknumb'];
$t_wday = (int)$report['totals_weekday'];
$totals_of_day[$t_wnumber][$t_wday] = (float)$report['totals_of_day'];
//$sum_of_week[$t_wnumber] = array_sum(array_column($totals_of_day, ''));
} // close foreach
var_dump(array_keys($totals_of_day));
var_dump($totals_of_day);
foreach ($totals_of_day as $w_n => $y) {
?>
<tr>
<th><?php echo $w_n; ?></th>
<td>More Details</td>
<?php
foreach ($y as $w_day => $saved) {
echo '<td>'. $curr.number_format($saved, 2) .'</td>';
} // close foreach
?>
<td><?php //echo $curr.$sum_of_week[]; ?></td>
</tr>
<?php
} // close 1st foreach
I tried so many options :(
Basically you need to iterate the days of the week and use the index in your array
foreach (range(1, 7) as $day) {
echo (isset($y[$day]) ? $y[$day] : '-');
}
Example:
<?php
$totals_of_day = [
7 => [3 => 150.8, 4 => 523.88, 5 => 95.32, 7 => 10.8],
8 => [1 => 13.78, 2 => 107.33, 4 => 8.49, 5 => 125.67],
9 => [1 => 71.3, 2 => 49.68, 6 => 95, 7 => 100.57],
10 => [1 => 18.34, 2 => 44.9, 3 => 55.7, 4 => 15.58]
];
?>
<table border="1" style="border-collapse: collapse;">
<tr>
<th>Week</th>
<th>Items</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
<th>Total Savings</th>
</tr>
<?php foreach ($totals_of_day as $w_n => $y) { ?>
<tr>
<th><?php echo $w_n; ?></th>
<td>More Details</td>
<?php foreach (range(1, 7) as $day) {
echo '<td>'. (isset($y[$day]) ? number_format($y[$day], 2) : '-') .'</td>';
} ?>
<td><?php echo number_format(array_sum($y), 2); ?></td>
</tr>
<?php } ?>
</table>

print html table from php array in particular way

I have a array that is dynamically generated and i am able to manipulate the data and print it in a table but I want to be able to print it differently.
This is what I have been able to do so far:
This is what I want to achieve
As you can see the array has multiple entries and for each entry I would like to create a new table and display the data like so:
There are some keys in the array I would prefer to leave out from being added to the table. the key names are: Id, CreatedDate, Incoming
Here is a short sample of what the array looks like:
[records] => Array
(
[0] => Array
(
[Id] =>
[CreatedDate] => 2016-02-18T02:24:57.000Z
[FromName] => Technical Support
[Incoming] =>
[MessageDate] => 2016-02-18T02:24:57.000Z
[Subject] => this is a test reply
[TextBody] => testt ref:_00D708cJQ._50080oYTuD:ref
[ToAddress] => outa#gmail.com
)
[1] => Array
(
[Id] =>
[CreatedDate] => 2016-02-17T13:36:52.000Z
[FromName] => Technical Support
[Incoming] => 1
[MessageDate] => 2016-02-17T13:36:08.000Z
[Subject] => MySupport Portal: Test Email via API
[TextBody] => this is a test email 4 ref:_00D708cJQ._50080oYTuD:ref
[ToAddress] => outa#gmail.com
)
Here is my current php code
$count = $response_array['size'] -1;
//print table headers
echo '<table border=1><tr>';
foreach( $response_array['records'][0] as $key => $value ) {
if($key !== 'Id') {
echo '<th>'.$key.'</th>';
}
}
echo '</tr><tr>';
//print table data
for ($i = 0; $i <= $count; $i++) {
foreach( $response_array['records'][$i] as $key => $value ) {
if($key !== 'Id') {
if($key === 'TextBody') {
echo '<td><pre>'.$value.'</pre></td>';
} else {
echo '<td>'.$value.'</td>';
}
}
}
echo '</tr><tr>';
}
echo "</tr></table>";
I know how to write the HTML but not sure how to tie in the php as im not sure how i can sort the headers to be in different part of the table.. in any case here is the html with dummy data as placeholders
<table border=1>
<tr>
<th>MessageDate</th>
<th>FromName</th>
<th>ToAddress</th>
</tr><tr>
<td>data</td>
<td>data</td>
<td>data</td>
</tr><tr>
<th colspan=3>Subject</th>
</tr><tr>
<td colspan=3>this is the subject</td>
</tr><tr>
<th colspan=3>TextBody</th>
</tr><tr>
<td colspan=3>this is the body</td>
</tr>
</table>
Okay, since you said you are able to do it for 1 line lets show you how to do it for all the line.
Just loop thourgh all the line like this.
<?php foreach( $response_array['records'] as $records): ?>
<table border=1>
<tr>
<th>MessageDate</th>
<th>FromName</th>
<th>ToAddress</th>
</tr><tr>
<td><?php echo $records['MessageDate'] ?></td>
<td><?php echo $records['FromName'] ?></td>
<td><?php echo $records['ToAddress'] ?></td>
</tr><tr>
<th colspan=3>Subject</th>
</tr><tr>
<td colspan=3><?php echo $records['Subject'] ?></td>
</tr><tr>
<th colspan=3>TextBody</th>
</tr><tr>
<td colspan=3><?php echo $records['TextBody'] ?></td>
</tr>
</table>
<?php endforeach; ?>
edit: Added php tags
Unex's answer is perfect. Here is another alternative:-
echo '<table border=1>';
foreach( $response_array['records'] as $key => $value ) {
if($key == 'MessageDate'){
echo "<tr>";
echo "<th>MessageDate</th>";
echo "<th>FromName</th>";
echo "<th>ToAddress</th>";
echo "</tr>";
echo "<tr>";
echo "<td>{$response_array['records'][$key]['MessageDate']}</td>";
echo "<td>{$response_array['records'][$key]['FromName']}</td>";
echo "<td>{$response_array['records'][$key]['ToAddress']}</td>";
echo "</tr>";
}
if($key == 'Subject'){
echo '<tr>';
echo "<th colspan='3'>Subject</th>";
echo "</tr>";
echo '<tr>';
echo "<td colspan='3'>{$response_array['records'][$key]['Subject']}</td>";
echo "</tr>";
}
if($key == 'TextBody'){
echo "<tr>";
echo "<th colspan='3'>TextBody</th>";
echo "</tr>";
echo "<tr>";
echo "<td colspan='3'>{$response_array['records'][$key]['TextBody']}</td>";
echo "</tr>";
}
}
echo "</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 ...

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:

php get the same index values from two arrays (outside foreach)

Have array named for example $data_debit_turnover
Array
(
[0] => Array
(
[VatReturnRowNumberForDebitTurnover] => 63
[Total] => 0.00
)
[1] => Array
(
[VatReturnRowNumberForDebitTurnover] => 64
[Total] => 44.28
)
)
Have HTML that need to look like this
<table><tr>
<td><strong>63</strong></td>
<td>0.00</td>
</tr><tr>
<td><strong>64</strong></td>
<td>44.28</td>
</tr></table>
At first tried with php foreach, but in such case instead of one table get multiple tables [0], [1] etc.
Then tried
<td><strong>64</strong></td>
<td><?php
if( $data_debit_turnover[1][VatReturnRowNumberForDebitTurnover] == '64'){
echo $data_debit_turnover[1][Total]. ' Total<br>';
}?>
</td>
but problem is with [1] etc. I do not know number of []; may be [1] and may be [30].
Tried something like this
$resultVatReturnRowNumberForDebitTurnover = array();
$resultTotal = array();
foreach($data_debit_turnover as $i => $result){
$resultVatReturnRowNumberForDebitTurnover[] = $result[VatReturnRowNumberForDebitTurnover];
$resultTotal[] = $result[Total];
}
<td><strong>64</strong></td>
<td><?php
if (in_array('64', $resultVatReturnRowNumberForDebitTurnover)) {
echo $resultTotal[1];
}?>
</td>
The same problem [1]. How to echo corresponding (index) value from the another array.
For example if 64 is the second value in array $resultVatReturnRowNumberForDebitTurnover then need to echo the second value from array $resultTotal.
Possibly there is some other way.
Please advice.
Showing what I did with foreach
<?php
foreach($data_debit_turnover as $i => $result){
?>
<table>
<tr>
<td><strong>63</strong></td>
<td>
<?php if($result[VatReturnRowNumberForDebitTurnover] = '63') {
echo $result[Total];
} ?>
</td>
</tr>
<tr>
<td><strong>64</strong></td>
<td>
<?php if($result[VatReturnRowNumberForDebitTurnover] = '64') {
echo $result[Total];
} ?>
</td>
</tr>
</table>
<?php
}
?>
Update Thanks to #user2340218 advice get some solution. For each <td> must use foreach. Possibly there is some better solution.
<table><tr>
<td><strong>64</strong></td>
<td><?php foreach($data_debit_turnover as $vatReturn){if($vatReturn['VatReturnRowNumberForDebitTurnover'] == '64') {echo $vatReturn['Total'];}}?></td>
</tr><tr>
<td><strong>67</strong></td>
<td><?php foreach($data_debit_turnover as $vatReturn){if($vatReturn['VatReturnRowNumberForDebitTurnover'] == '67') {echo $vatReturn['Total'];}}?></td>
</tr></table>
Solution Finally used solution #Daniel P advised.
$resultVatReturnRowNumberForDebitTurnover = array();
$resultTotal = array();
foreach($data_debit_turnover as $i => $result){
$resultVatReturnRowNumberForDebitTurnover[] = $result[VatReturnRowNumberForDebitTurnover];
$resultTotal[] = $result[Total];
}
$VatReturnRowNumberForDebitTurnoverModified = array_combine($resultVatReturnRowNumberForDebitTurnover, $resultTotal);
<table>
<tr>
<td><strong>62</strong></td>
<td>
<?php echo $VatReturnRowNumberForDebitTurnoverModified[62]; ?>
</td>
</tr>
<tr>
<td><strong>63</strong></td>
<td>
<?php echo $VatReturnRowNumberForDebitTurnoverModified[63]; ?>
</td>
</tr>
</table>
Actually have to accept #Daniel P answer:) But as understand can not accept 2 answers
I am guessing that VatReturnRowNumberForDebitTurnover numbers are unique so your array should look like this :
Array
(
[63] => 0.00
[64] => 44.28
)
The array index is your VatReturnRowNumberForDebitTurnover and the value is your total.
To test if a VatReturnRowNumberForDebitTurnover has a value your simply use isset()
if (isset($array[63])) {
echo $array[63]
}
Building the table :
<table>
<?php foreach($data_debit_turnover as $i => $total){ ?>
<tr>
<td><strong><?php echo $i; ?></strong></td>
<td><?php echo $total; ?></td>
</tr>
<?php } ?>
</table>
Do you mean this?
<table>
<?php foreach($data_debit_turnover as $vatReturn){ ?>
<tr>
<td><strong><?php print $vatReturn['VatReturnRowNumberForDebitTurnover'] ?></strong></td>
<td><?php print $vatReturn['total'] ?></td>
</tr>
<?php } ?>
</table>
Use foreach like this:
<table>
<?php
foreach ($Array as $item)
{
echo '<tr>';
echo '<td><strong>' . $item['VatReturnRowNumberForDebitTurnover'] . '</strong></td>';
echo '<td>' . $item['Total'] . '</td>';
echo '</tr>'
}
?>
</table>

Categories