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 ...
Related
What would be the best way to print an HTML table with an array of arrays in php? Each array key would be the head of the table, and the sub-array items the table cells.
arr = [
key_1 ->
- key_1_val_1
- key_1_val_2
- key_1_val_3
key_2 ->
- key_2_val_1
- key_2_val_2
- key_2_val_3
]
Expected output:
<table>
<tr>
<td>key_1</td>
<td>key_2</td>
</tr>
<tr>
<td>key_1_val_1</td>
<td>key_2_val_1</td>
</tr>
...
</table>
Any idea?
Tnx
Not success:
<table>
<thead>
<tr>
<?php foreach ( array_keys( $get_cards ) as $head ): ?>
<th><?php esc_html_e( get_the_title( $head ) ); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<tr>
<?php foreach ( $get_cards as $cols ): ?>
<?php $row_end = count( $get_cards ); ?>
<?php $colum_end = count( $cols ); ?>
<?php $count_rows ++; ?>
<?php foreach ( $cols as $col ): ?>
<?php $count_columns ++; ?>
<td>1</td>
<?php endforeach; ?>
<?php if ( $count_rows % 2 === 0 ): ?>
<?php endif; ?>
<?php $count_columns = 0; ?>
<?php endforeach; ?>
<?php $count_rows = 0; ?>
</tr>
</tbody>
</table>
Solved.
This is my solution: https://gist.github.com/angelorocha/bdd10af73d047709553ef225500fe993
The code of your project is to create a new array for creating a comparative table. We can do it by manipulating index in your case.
This is the main logic for creating a new array.
<?php
$i = 0;
$arr = [];
foreach ( $age as $cols ): ?>
<?php
$j = 0;
foreach ( $cols as $vals ):
$arr[$j][$i] = $vals;
$j++;
endforeach;
$i++;
?>
this is the full code.
<!DOCTYPE html>
<html>
<body>
<?php
$age = [
"No"=>["35", "24", "60"],
"Owner"=>["Peter", "John", "David"],
"Location"=>["Hong Kong", "New York", "Los Angeles"]
];
?>
<table>
<thead>
<tr>
<?php
foreach ( $age as $key=>$value ): ?>
<th><?php echo $key; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<tr>
<?php
$i = 0;
$arr = [];
foreach ( $age as $cols ): ?>
<?php
$j = 0;
foreach ( $cols as $vals ):
$arr[$j][$i] = $vals;
$j++;
endforeach;
$i++;
?>
<?php endforeach;
foreach($arr as $cols):
echo "<tr>";
foreach($cols as $val):
echo "<td>".$val."</td>";
endforeach;
echo "</tr>";
endforeach;
?>
</tr>
</tbody>
</table>
</body>
</html>
Use a set of nested loops to transpose the multidimensional array data (as well as transferring the first level keys as the new first row of data).
Then use a basic loop to print the rows as html. The way implode() is used, it won't matter if the number of columns changes -- it will create as many columns as are needed.
Code: (Demo)
$arr = [
'key_1' => ['A', 'B', 'C'],
'key_2' => ['D', 'E', 'F'],
];
$transpose = [];
foreach ($arr as $k => $row) {
$transpose[0][] = $k;
foreach ($row as $i => $v) {
$transpose[$i + 1][] = $v;
}
}
echo "<table border=1>\n";
foreach ($transpose as $values) {
echo "<tr><td>" . implode('</td><td>', $values) . "</td></tr>\n";
}
echo '</table>';
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>';
This code shows every info from an XML. I want to only display row number one (first from/to, symbol temperature etc)
<?php
$url = ('https://www.yr.no/sted/Norge/oslo/oslo/oslo/varsel_time_for_time.xml');
$feed = simplexml_load_file($url) or die('Can not connect to server');
$result = array();
foreach ($feed->forecast->tabular->time as $content) {
array_push($result, [ "from" => (string)$content['from'],
"to" => (string)$content['to'],
'symbol' => (string)$content->symbol['name'],
'symbol-icon' => (string)$content->symbol['var'],
'temperature' => (string)$content->temperature['value'],
'windDirection' => (string)$content->windDirection['name'],
'windSpeed' => (string)$content->windSpeed['mps'],
'windType' => (string)$content->windSpeed['name'],
]);
}
?>
<button class="collapsible"><div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<?php foreach ($result as $value) { ?>
<tr>
<td>Oslo</td>
<td><?php echo date("j. M", strtotime($value['from'])); ?> kl.<?php echo date("G", strtotime($value['from'])); ?></td>
<td><img src="http://yr.github.io/weather-symbols/png/100/<?php echo $value['symbol-icon'];?>.png" /></td>
<td><?php echo $value['temperature'] ?> °C</td>
<td><?php echo $value['windType'] ?>, <?php echo $value['windSpeed'] ?> m/s fra <?php echo $value['windDirection'] ?></td>
<td>Longtherm</td>
<td>Hour</td>
</tr>
<?php } ?>
</tbody>
</table>
</div></button>
quite unexperienced, any help is greatly appreciated
Just one of the rows? Remove the foreach! Just use $result[0] in place of $value. :-)
A defined number of rows? Use a for loop:
for ($x = 0; $x < $limit; $x++) {
$value = $result[$x];
// etc
}
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>
How do it turn a multidimensional array like:
$fruits['apples']['blue'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['apple']['red'] = 34;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
into a cross referenced table like:
alt text http://1updesign.org/uploads/p24.png
$cols = array('blue', 'red', 'orange');
echo '<table>';
echo '<thead><tr><td></td><th scope="col">' . implode('</th><th scope="col">', $cols) . '</th></tr></thead>';
echo '<tbody>';
foreach($fruits as $label => $row)
{
echo '<tr>';
echo '<th scope="row">' . $label . '</th>';
foreach($cols as $k)
{
echo '<td>' . (isset($row[$k]) ? $row[$k] : 0) . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
You’ll want some HTML escaping and such, but that’s the gist of it.
Your array is bad designed. How should one know, that apples is the same as apple. Your array should be constructed this way:
$fruits['apples']['blue'] = 24;
$fruits['apples']['read'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
Then iterating is easy. The first level of the array are the rows. So:
<?php
$column_head = array();
foreach($fruits as $key => $value) {
$column_head = array_merge($column_head, array_keys($value));
}
$column_head = array_unique($column_head);
print_r($column_head);
?>
<table>
<tr>
<th></th>
<?php foreach($column_head as $head): ?>
<th><?php echo $head; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach($fruits as $fruit => $amount): ?>
<tr>
<td><?php echo $fruit ?></td>
<?php foreach($column_head as $head): ?>
<td><?php echo isset($amount[$head]) ? $amount[$head] : 0 ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
This generates which columns to use on fly, but it can be hardcoded which might be easier. As the code uses a lot loops it might be not that efficient...