Print a html table with transposed data from a multidimensional array - php

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>';

Related

How to fetch data in table group by other column in PHP

I have a record like this in database:
section_id description level_id
1 Amethyst 1
2 Betelguise 1
3 Daisy 2
4 Rose 2
I want it to display in my php table just like this:
Level 1
Amethyst
Betelguise
Level 2
Daisy
Rose
Can anyone please help me? I am new at this.
Here's my code:
<table>
<thead>
<tr>
<th>Descriptions</th>
<th>Level</th>
</tr>
</thead>
<?php $sql = "SELECT * FROM tbl_sectiontaken"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while($row = $result->fetch_assoc()) { ?>
<?php $id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id']; ?>
<tbody>
<tr>
<td style="text-transform:capitalized;">
<?php echo $desc; ?>
</td>
<td style="text-transform:capitalized;">
<?php echo $gr; ?>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
But it gives me this result in table:
Descriptions Level
Amethyst 1
Betelguise 1
Daisy 2
Rose 2
You can use group_concat function for this. Use below code if suits your requirements
<?php $sql = "SELECT level_id,GROUP_CONCAT(description) AS description FROM series group by level_id"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while ($row = $result->fetch_assoc()) { ?>
<?php
$id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id'];
$leveArr[$gr][] = $desc;// Create an array with level and description
} } ?>
</tbody>
<table>
<tr><!-- header-->
<?php foreach ($leveArr as $key => $value) { ?>
<td><?php echo "LEVEL " . $key ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($leveArr as $key => $value) {
foreach ($value as $key_1 => $data) { ?>
<td><?php
$data = explode(",", $data);
foreach ($data as $key_2 => $final) {
echo $final . "<br>";
}
?></td>
<?php }
} ?>
</tr>
</table>
Updated
Check the sandbox example
Change query with GROUP_CONCAT
SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id
And After.They return array like this
$arr=[['description'=>'a,b,c,d','level_id'=>'1','heigher'=>'4'],['description'=>'a,b,c,d','level_id'=>'2','heigher'=>'4']]; ?>
Then Finally Create Table as like this
$sql="SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id";
$result = $conn->query($sql);
$arr =[];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$arr[]=$row;
}
}
<table>
<thead>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?='level'.$value['level_id']?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
$arr = array_filter($arr,function($a=[]){
return $a['level_id'] != 0
}) //filter level not a zero
$h = max(array_map(function($a=[]){
return $a['heigher']; //filter array['heigher only']
},$arr)); // its get the heighest length of description value like [10,15,100]=>100
foreach ($arr as $key => $value){
$value['description'] = !empty($value['description']) ?explode(',',$value['description']):'';
$arr[$key]=$value;
}
?>
<?php for ($i=0; $i < $h[0]; $i++) {?>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?=isset($value['description'][$i])? $value['description'][$i] :''?></th>
<?php endforeach; ?>
</tr>
<?php }?>
</tbody>
</table>

PDO FETCH all return one row in HTML

foreach($ligne as $value){
$result = $bdd->query('SELECT count(d.DNUMERO) as nbr, SUM(d.DINIPPL) as total FROM dossier d, cliregroup c, doinfsup i WHERE i.DSNUMERO = d.DNUMERO AND d.DNUMCLI = c.NUMCLI AND i.INFOSUPPLM REGEXP "([1][4-6][0-9a-zA-Z]{6}[0-9]{4})" AND INFOSUPPLM NOT REGEXP "([0-1][0-4][0-9a-zA-Z]{6}[0-9]{4})" AND i.DSNUMERO LIKE "16%" AND c.CODEREGROUP LIKE "'.$value.'"');
$table = $result->fetchAll();
print_r($table);
}
<?php include_once('header.html'); ?>
My $table return one row not the full table (the last row). In the php file it's good:
<?php print_r($table); ?>
<table class="table">
<?php foreach ($table as $key => $q): ?>
<?php foreach ($secteur as $key => $s): ?>
<tr>
<th><?php echo $key; ?></th>
<td><?php echo $q['nbr']; ?></td>
<td><?php echo $q['total']; ?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</table>
</body>
</html>
You are overwriting $table each time through the loop. Try an array:
$table[] = $result->fetchAll();
Other issues:
<?php foreach ($table as $key => $q): ?>
<?php foreach ($secteur as $key => $s): ?>
You overwrite $key with the second loop.
Where does $secteur come from? It's not defined. Maybe you meant $q?

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 limit foreach loop to three loops

how to limit this loop ..just thee loops..thanks for helping
<?php
foreach($section['Article'] as $article) :
?>
<tr>
<td>
<?php
if ($article['status'] == 1) {
echo $article['title'];
}
?>
</td>
<td>
<?php
if($article['status']== 1) {
echo ' '.$html->link('View', '/articles/view/'.$article['id']);
}
?>
</td>
</tr>
<?php
endforeach;
?>
Slice the array.
foreach(array_slice($section['Article'], 0, 3) as $article ):
first, prepare your data
$i = 1;
$data = array();
foreach($section['Article'] as $article ) {
if($article['status']== 1) {
$article['link'] = $html->link('View', '/articles/view/'.$article['id']);
$data[] = $article;
if ($i++ == 3) break;
}
}
$section['Article'] = $data;
then display it
<?php foreach($section['Article'] as $article ): ?>
<tr>
<td><?php echo $article['title'] ?></td>
<td> <?php echo $article['link']?></td>
</tr>
<?php endforeach ?>
This will help if your array is numerically indexed
foreach($section['Article'] as $i => $article ):
if ($i > 3) break;
Otherwise - manually increment the counter:
$i = 0;
foreach($section['Article'] as $article ):
if ($i++ > 3) break;
It'd be easier to use a for() loop to do this, but to answer the question:
<?
$i = 0;
foreach ($section['Article'] AS $article):
if ($i == 3) { break; }
?>
...
<?
$i++;
endforeach
?>
A foreach loop wouldn't be the best if you need to limit it. Try using a for loop.
<?php
for(i=1; i<=3; i++)
{
$article = $section['Article'];
?>
<tr>
<td><?php if($article['status']== 1){echo $article['title'];} ?></td>
<td><?php if($article['status']== 1){echo ' '.$html->link('View', '/articles/view/'.$article['id']);}?></td>
</tr>
<?php } ?>
This code will make the text loop 3 times.
Awesome one must try this one
<?php $count = 0; $pages = get_pages('child_of=1119&sort_column=post_date&sort_order=desc'); foreach($pages as $page) {
$count++;
if ( $count < 50) { // only process 10 ?>
<div class="main_post_listing"> <?php echo $page->post_title ?><br /></div>
<?php
} } ?>

printing multi dimentional array

i have this multi dimentional array that i want to print into a table having each record/item go into its own row but it goes column wise. this is the output that im getting: http://mypetshopping.com/product.php
ps: the value of $product will by dynamic based on what product is being viewed.
<?php
session_start();
?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Hash</th>
<th>Quantity</th>
<th>Size</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<?php
function addCart($product, $quantity, $size,$color) {
$hash = md5($product);
$_SESSION['cart'][$product]['name'] = $product;
$_SESSION['cart'][$product]['hash'] = $hash;
$_SESSION['cart'][$product]['quantity'] = $quantity;
$_SESSION['cart'][$product]['size'] = $size;
$_SESSION['cart'][$product]['color'] = $color;
}
addCart('Red Dress',1,'XL','red');
addCart('Blue Dress',1,'XL','blue');
addCart('Slippers',1,'XL','orange');
addCart('Green Hat',1,'XXXL','green');
$cart = $_SESSION['cart'];
foreach($cart as $product => $array) {
foreach($array as $key => $value) {
?>
<tr>
<td><?=$value;?></td>
<td><?=$value;?></td>
<td><?=$value;?></td>
<td><?=$value;?></td>
<td><?=$value;?></td>
</tr>
<?php
}
}
?>
I think your looping code should be written as:
<?php foreach( $cart as $product => $array ) { ?>
<tr>
<?php foreach( $array as $key => $value ) { ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
<?php } ?>
try altering your code to:
foreach($cart as $product => $array) { ?>
<tr>
<?php
foreach($array as $key => $value) {
?>
<td><?=$value;?></td>
<?php
}
?>
</tr>
<?php
}
<?php
echo "<ul>";
for ( $layer = 0; $layer < 3; $layer++ )
{
echo "<li>The layer number $layer";
echo "<ul>";
for ( $row = 0; $row < 3; $row++ )
{
echo "<li>The row number $row";
echo "<ul>";
for ( $col = 0; $col < 3; $col++ )
{
echo "<li>".$shop[$layer][$row][$col]."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
?>
http://www.webcheatsheet.com/php/multidimensional_arrays.php

Categories