can you give me idea how to implement this idea for "dynamic" html table.
I have an array
$arr = array(
array(
'label' => 'First name',
'data' => array(
array('fname' => 'John'),
array('fname' => 'Ralph'),
),
),
array(
'label' => 'Last name',
'data' => array(
array('lname' => 'Doe'),
array('lname' => 'Loren'),
),
),
array(
'label' => 'Description',
'data' => array(
array('description' => 'Something bout John'),
array('description' => 'Something about Ralph'),
),
),
);
Now from the keys 'label' im creating the table columns
---------------------------------------
|First Name | Last Name | Description |
---------------------------------------
The problem is how to put 'fname' keys in the first column, 'lname' in the second and 'description' in the third.
With this part of code im trying to put the data in all columns
private function tableBody()
{
$data = $this->data;
$table = '<tbody>';
foreach($data as $key => $value){
foreach($value['data'] as $k => $v){
$table .= '<tr>';
foreach($v as $col => $name){
$table .= '<td>' . $name . '</td>';
}
$table .= '</tr>';
}
}
$table .= '</tbody>';
return $table;
}
Also my idea is not to hard code array keys for multiple usage(except label and data).
First I would remap the data to process it in loops.
$labels = [];
$rows = [];
foreach($arr as $column) {
$label = $column['label'];
$labels[] = $label;
foreach($column['data'] as $key => $value) {
$rows[$label][] = $value;
}
}
Now print out the labels with the headline.
echo "<table>\n";
echo "<tr>";
foreach($labels as $label) echo "<th>{$label}</th>";
echo "</tr>\n";
Iterate through the rows and create the HTML.
$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);
while($rowCount) {
echo "<tr>";
for ($i = 0; $i < $labelCount; $i++) {
$current = array_shift($rows[$labels[$i]]);
$value = reset($current);
echo "<td>{$value}</td>";
}
echo "</tr>\n";
$rowCount--;
}
echo "</table>\n";
This gives a table like below
<table>
<tr><th>First name</th><th>Last name</th><th>Description</th></tr>
<tr><td>John</td><td>Doe</td><td>Something bout John</td></tr>
<tr><td>Ralph</td><td>Loren</td><td>Something about Ralph</td></tr>
</table>
You need to manipulate the initial array to reduce it to something more manageable. You could brute force your way like so:
function reduce($data) {
$ret = [];
foreach ($data as $d1) {
// column header could have been fetched here
foreach ($d1 as $k2 => $d2) {
// keeping track of what label we need
$key = '';
// keeping the values together
$child = [];
// discarding non arrays
if (is_array($d2)) {
foreach ($d2 as $d3) {
// identifier fetch from this level
foreach ($d3 as $k4 => $d4) {
$key = $k4;
$child[] = $d4;
}
}
}
// assigning back to the main array only if we have something
if (!empty($child)) {
$ret[$key] = $child;
}
}
}
return $ret;
}
That will return the following:
Array
(
[fname] => Array
(
[0] => John
[1] => Ralph
)
[lname] => Array
(
[0] => Doe
[1] => Loren
)
[description] => Array
(
[0] => Something bout John
[1] => Something about Ralph
)
)
I have this code to show a table in PHP:
<?php
$harvest = Array (
Array (
Array (
'PRODUCT' => 'ROSE' ,
'VARIETY' => 'ADELE',
'GOLD' => 160,
'NORMAL' => 0 ,
'TOTAL' => 160
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ALESSO' ,
'GOLD' => 1320 ,
'NORMAL' => 550,
'TOTAL' => 1870
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ANASTACIA' ,
'GOLD' => 440 ,
'NORMAL' => 150 ,
'TOTAL' => 590
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1' ,
'GOLD' => 420 ,
'NORMAL' => 120 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1',
'GOLD' => 440 ,
'NORMAL' => 100 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2',
'GOLD' => 640,
'NORMAL' => 0,
'TOTAL' => 640
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2' ,
'GOLD' => 440,
'NORMAL' => 440,
'TOTAL' => 880
)
)
);
$arrayThead = array();
for ($i=0; $i < count($harvest) ; $i++) {
array_push($arrayThead, array_keys($harvest[$i][0]));
}
$totalByProduct = array();
foreach ($harvest as $items) {
foreach ($items as $item) {
if(!key_exists($item['PRODUCT'], $totalByProduct)){
$totalByProduct[$item['PRODUCT']] = $item;
unset($totalByProduct[$item['PRODUCT']]['VARIETY']);
continue;
}
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$totalByProduct[$item['PRODUCT']][$th] += $item[$th];
}
}
}
}
}
$arrayfoot= array();
foreach ($harvest as $key => $value) {
foreach ($value as $harv) {
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$arrayfoot[$th] += $harv[$th];
}
}
}
}
}
$arrayfoot= array();
foreach ($harvest as $key => $value) {
foreach ($value as $harv) {
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$arrayfoot[$th] += $harv[$th];
}
}
}
}
}
$arrayComplete = array();
for ($i=0; $i < count($arrayThead) ; $i++) {
for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
array_push($arrayComplete, $arrayThead[$i][$j]);
}
}
}
$arrayFinal = array();
for ($j=0; $j < count($arrayComplete) ; $j++) {
array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
}
// exit;
$body = '';
$body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
$body .= '<thead style="background-color:#f3f4f5;">';
$body .= '<tr>';
for ($i=0; $i < count($arrayThead) ; $i++) {
for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
$body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
}else{
$body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
}
}
}
$body .= '</tr>';
$body .= '</thead>';
$body .= '<tbody>';
for ($k=0; $k < count($harvest); $k++) {
for ($a=0; $a < count($harvest[$k]) ; $a++) {
$body .= '<tr>';
for ($i=0; $i < count($arrayThead) ; $i++) {
for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
$body .= '<td style="border: 1px solid black;font-size:12px;">'.$harvest[$k][$a][$arrayThead[$i][$j]].'</td>';
}else{
$body .= '<td style="border: 1px solid black; text-align:right;font-size:12px;">'.number_format($harvest[$k][$a][$arrayThead[$i][$j]]).'</td>';
}
}
}
$body .= '</tr>';
foreach ($totalByProduct as $key => $value) {
if($value["PRODUCT"] == $harvest[$k][$a]['PRODUCT']){
$body .= '<tr>';
$body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;">TOTAL '.$value["PRODUCT"].'</th>';
$body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;"></th>';
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$body .= '<th style="border: 1px solid black;text-align:right;font-size:12px;">'.number_format($value[$th]).'</th>';
}
}
}
$body .= '</tr>';
}
}
}
}
$body .= '</tbody>';
$body .= '<tfoot>';
$body .= '<tr>';
$body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
$body .= '<th style="border: 1px solid black;"></th>';
for ($i=0; $i < count($arrayFinal) ; $i++) {
$body .= '<th style="border: 1px solid black;text-align:right;">'.number_format($arrayFinal[$i]).'</th>';
}
$body .= '</tr>';
$body .= '</tfoot>';
$body .= '</table>';
echo $body;
I need to place a row with the total of GOLD, NORMAL and TOTAL inside the table, but according the product.
If you want to see how the code works you can copy the code and past in this page: PHPTESTER
I need to show the table something like this:
-------------------------------------------------------------------
PRODUCT | VARIETY | GOLD | NORMAL | TOTAL |
-------------------------------------------------------------------
ROSE | ADELE | 160 | 0 | 160 |
-------------------------------------------------------------------
ROSE | ALESSO | 1320 | 550 | 1870 |
-------------------------------------------------------------------
ROSE | ANASTACIA | 440 | 150 | 590 |
-------------------------------------------------------------------
TOTAL ROSE | | 1920 | 700 | 2620 |
-------------------------------------------------------------------
ROSE1 | ANASTACIA1 | 420 | 120 | 540 |
-------------------------------------------------------------------
ROSE1 | ANASTACIA1 | 440 | 100 | 540 |
-------------------------------------------------------------------
TOTAL ROSE1 | | 860 | 220 | 1080 |
-------------------------------------------------------------------
ROSE2 | ANASTACIA2 | 640 | 0 | 640 |
-------------------------------------------------------------------
ROSE2 | ANASTACIA2 | 440 | 440 | 880 |
-------------------------------------------------------------------
TOTAL ROSE2 | | 1080 | 440 | 1520 |
-------------------------------------------------------------------
TOTAL GENERAL| | 3860 | 1360 | 5220 |
-------------------------------------------------------------------
I hope that someone can help me thanks!
Here is the code. You can make modification to the code
foreach($harvest[0] as $key=>$value){
$new_array[$value['PRODUCT']][] = $value;
}
echo '<table cellspacing="5" cellpadding="5" border="1px solid #ccc">';
echo "<tr>
<th>PRODUCT</th>
<th>VARIETY</th>
<th>GOLD</th>
<th>NORMAL</th>
<th>TOTAL</th>
</tr>";
$total_gold = $total_normal = $total_total = 0;
foreach($new_array as $key=>$value){
$gold[$key] = $normal[$key] = $total[$key] = 0;
if(is_array($value)){
foreach($value as $k=>$v){
$gold[$key] += $v['GOLD'];
$normal[$key] += $v['NORMAL'];
$total[$key] += $v['TOTAL'];
echo "<tr>";
echo "<td>".$key."</td>";
echo "<td>".$v['VARIETY']."</td>";
echo "<td>".$v['GOLD']."</td>";
echo "<td>".$v['NORMAL']."</td>";
echo "<td>".$v['TOTAL']."</td>";
echo "<tr>";
}
echo "<tr><td><b>Total ".$key."</b></td><td></td><td>".$gold[$key]."</td><td>".$normal[$key]."</td><td>".$total[$key]."</td></tr>";
$total_gold +=$gold[$key];
$total_normal +=$normal[$key];
$total_total += $total[$key];
}
}
echo "<tr><td><b>TOTAL GENERAL</b></td><td></td><td>".$total_gold."</td><td>".$total_normal."</td><td>".$total_total."</td></tr>";
echo "</table>";
<?php
$harvest = Array (
Array (
Array (
'PRODUCT' => 'ROSE' ,
'VARIETY' => 'ADELE',
'GOLD' => 160,
'NORMAL' => 0 ,
'TOTAL' => 160
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ALESSO' ,
'GOLD' => 1320 ,
'NORMAL' => 550,
'TOTAL' => 1870
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ANASTACIA' ,
'GOLD' => 440 ,
'NORMAL' => 150 ,
'TOTAL' => 590
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1' ,
'GOLD' => 420 ,
'NORMAL' => 120 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1',
'GOLD' => 440 ,
'NORMAL' => 100 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2',
'GOLD' => 640,
'NORMAL' => 0,
'TOTAL' => 640
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2' ,
'GOLD' => 440,
'NORMAL' => 440,
'TOTAL' => 880
)
)
);
$prods = array();
$prevprod = "";
$total_gold = 0;
$total_normal = 0;
$total_prod = 0;
$total = 0;
foreach($harvest[0] as $key => $val){
$pos = $key;
$obj = $val;
$total_prod = $obj["GOLD"]+$obj["NORMAL"];
if($obj["PRODUCT"]==$prevprod || $prevprod==""){
$prods[] = array($obj["PRODUCT"],$obj["VARIETY"],$obj["GOLD"],$obj["NORMAL"],$obj["TOTAL"]);
$total_gold = $total_gold + $obj["GOLD"];
$total_normal = $total_normal + $obj["NORMAL"];
$total_prod = $total_prod + $obj["TOTAL"];
$total = $total + $total_prod;
}else{
$prods[] = array( "TOTAL ".$prevprod, "", $total_gold,$total_normal,$total_prod);
$total_gold = 0;
$total_normal = 0;
$total_prod = 0;
}
$prevprod = $obj["PRODUCT"];
}
$prods[] = array( "TOTAL ".$prevprod, "", $total_gold,$total_normal,$total_prod);
// exit;
$body = '';
$body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
$body .= '<thead style="background-color:#f3f4f5;">';
$body .= '<tr>';
$body .= '<th>PRODUCT</th><th>VARIETY</th><th>GOLD</th><th>NORMAL</th><th>TOTAL</th>';
$body .= '</tr>';
$body .= '</thead>';
$body .= '<tbody>';
foreach($prods as $p){
$body .= '<tr><td>'.$p[0].'</td><td>'.$p[1].'</td><td>'.$p[2].'</td><td>'.$p[3].'</td><td>'.$p[4].'</td><tr>';
}
$body .= '</tbody>';
$body .= '<tfoot>';
$body .= '<tr>';
$body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
$body .= '<th style="border: 1px solid black;"></th><th style="border: 1px solid black;"></th><th style="border: 1px solid black;"></th>';
$body .= '<th>'.$total.'</th>';
$body .= '</tr>';
$body .= '</tfoot>';
$body .= '</table>';
echo $body;
Here is the example code:
<?php
$arr = array(
array(
'company' => array(
'code' => 'ccd1',
'name' => 'cnm1'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
)
)
) ,
array(
'company' => array(
'code' => 'ccd2',
'name' => 'cnm2'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
) ,
array(
'code' => 'pcd3',
'name' => 'pnm3'
)
)
)
);
echo "<pre>"; print_r($arr); echo "</pre>";
$AI = 1;
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
foreach($value['products'] as $value2){
echo " ".$value2['name']."<br />";
}
}
I don't know how to explain it, but what I want is to add auto increment in sub foreach loop, like this:
1.cnm1 (2)
1.pnm1
2.pnm2
2.cnm2 (3)
1.pnm1
2.pnm2
3.pnm3
Usually you can just use the foreach keys plus one. As another alternative, if this is just for presentation, just use ordered lists:
echo '<ol>';
foreach($arr as $ar1) {
echo '<li>' . $ar1['company']['name'] . ' (' . count($ar1['products']) . ')</li>';
echo '<ol>';
foreach($ar1['products'] as $ar2) {
echo "<li>{$ar2['name']}</li>";
}
echo '</ol>';
}
It'll number those items accordingly. No need for addition. Plus you can use CSS to style the list,
You can access the key/index of an foreach :
foreach($arr as $i => $value){
$total_products = count($value['products']);
echo ($i+1).'.'.$value['company']['name'].' ('.$total_products .')<br />';
foreach($value['products'] as $j => $value2){
echo ' '.($j+1).'.'.$value2['name'].'<br />';
}
}
Here you go.
$arr = array(array('company'=>array('code'=>'ccd1', 'name'=>'cnm1'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'))), array('company'=>array('code'=>'ccd2', 'name'=>'cnm2'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'), array('code'=>'pcd3', 'name'=>'pnm3'))));
echo "<pre>";
print_r($arr);
echo "</pre>";
$AI = 1;
foreach($arr as $value)
{
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$k = 0;
foreach($value['products'] as $value2)
{
echo " ".$k++.". ".$value2['name']."<br />";
}
}
This also worked for me:
foreach($value['products'] as $key2=>$value2){
$AI2 = $key2+1;
echo " ".$AI2.".{$value2['name']}<br />";
}
You can try this:
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$sub=1;
foreach($value['products'] as $value2){
echo " ".$sub++.'.'.$value2['name']."<br />";
}
}
I am having a multidimensional array with same values like this,
[documents] => Array
(
[0] => Array
(
[doc_id] => 3
[doc_type] => driving_licence
[expiry_date] => 2015-11-26
[added_date] => 2015-11-16
)
[1] => Array
(
[doc_id] => 3
[doc_type] => driving_licence
[expiry_date] => 2015-11-26
[added_date] => 2015-11-16
)
)
So now I need to echo this array in a html table with single <tr>.
This is how I tried it :
foreach ($userData as $key => $value) {
$i=0;
foreach ($value['documents'] as $k => $v) {
$i++;
$html = "<tr>\n";
$html .= " <td class='center'>{$i}</td>";
$html .= " <td>{$v['doc_type']}</td>";
$html .= " <td>{$v['expiry_date']}</td>";
$html .= " <td>{$v['added_date']}</td>";
$html .= "</tr>\n";
echo $html;
}
}
But its repeating table <tr> with same values.
Can anybody tell me how to avoid this?
Thank you.
As requested, here is an example for you.
$userData = $input = array_map("unserialize", array_unique(array_map("serialize", $userData)));
foreach ($userData as $key => $value) {
$i=0;
foreach ($value['documents'] as $k => $v) {
$i++;
$html = "<tr>\n";
$html .= " <td class='center'>{$i}</td>";
$html .= " <td>{$v['doc_type']}</td>";
$html .= " <td>{$v['expiry_date']}</td>";
$html .= " <td>{$v['added_date']}</td>";
$html .= "</tr>\n";
echo $html;
}
}
That will give you a table with 1 <tr> row.
this is the way i would do what you are trying to do:
$movies = array
(
array('Office Space' , 'Comedy' , 'Mike Judge' ),
array('Matrix' , 'Action' , 'Andy / Larry Wachowski' ),
array('Lost In Translation' , 'Comedy / Drama' , 'Sofia Coppola' ),
array('A Beautiful Mind' , 'Drama' , 'Ron Howard' ),
array('Napoleon Dynamite' , 'Comedy' , 'Jared Hess' )
);
echo "<table border=\\"1\\">";
echo "<tr><th>Movies</th><th>Genre</th><th>Director</th></tr>";
for ( $row = 0; $row < count($movies); $row++ )
{
echo "<tr><td>";
for ( $column = 0; $column < count($movies); $column++ )
{
echo $movies[$row][$column] ;
}
echo "<td></tr>";
}
How do I create a HTML table from a PHP array? A table with heading as 'title', 'price', and 'number'.
$shop = array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7 ),
);
It would be better to just fetch the data into array like this:
<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
array("title"=>"daisy", "price"=>0.75 , "number"=>25),
array("title"=>"orchid", "price"=>1.15 , "number"=>7)
);
?>
And then do something like this, which should work well even when you add more columns to your table in the database later.
<?php if (count($shop) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
Here's mine:
<?php
function build_table($array){
// start table
$html = '<table>';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . htmlspecialchars($key) . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
$array = array(
array('first'=>'tom', 'last'=>'smith', 'email'=>'tom#example.org', 'company'=>'example ltd'),
array('first'=>'hugh', 'last'=>'blogs', 'email'=>'hugh#example.org', 'company'=>'example ltd'),
array('first'=>'steph', 'last'=>'brown', 'email'=>'steph#example.org', 'company'=>'example ltd')
);
echo build_table($array);
?>
<table>
<tr>
<td>title</td>
<td>price</td>
<td>number</td>
</tr>
<? foreach ($shop as $row) : ?>
<tr>
<td><? echo $row[0]; ?></td>
<td><? echo $row[1]; ?></td>
<td><? echo $row[2]; ?></td>
</tr>
<? endforeach; ?>
</table>
You can also use array_reduce
array_reduce — Iteratively reduce the array to a single value using a callback function
example:
$tbody = array_reduce($rows, function($a, $b){return $a.="<tr><td>".implode("</td><td>",$b)."</td></tr>";});
$thead = "<tr><th>" . implode("</th><th>", array_keys($rows[0])) . "</th></tr>";
echo "<table>\n$thead\n$tbody\n</table>";
This is one of de best, simplest and most efficient ways to do it.
You can convert arrays to tables with any number of columns or rows.
It takes the array keys as table header. No need of array_map.
function array_to_table($matriz)
{
echo "<table>";
// Table header
foreach ($matriz[0] as $clave=>$fila) {
echo "<th>".$clave."</th>";
}
// Table body
foreach ($matriz as $fila) {
echo "<tr>";
foreach ($fila as $elemento) {
echo "<td>".$elemento."</td>";
}
echo "</tr>";
}
echo "</table>";}
echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
echo "<tr>";
foreach($v as $vv){
echo "<td>{$vv}</td>";
}
echo "<tr>";
}
echo "</table>";
echo '<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>';
foreach($shop as $id => $item) {
echo '<tr><td>'.$item[0].'</td><td>'.$item[1].'</td><td>'.$item[2].'</td></tr>';
}
echo '</table>';
<table>
<thead>
<tr><th>title</th><th>price><th>number</th></tr>
</thead>
<tbody>
<?php
foreach ($shop as $row) {
echo '<tr>';
foreach ($row as $item) {
echo "<td>{$item}</td>";
}
echo '</tr>';
}
?>
</tbody>
</table>
Here is my answer.
function array2Html($array, $table = true)
{
$out = '';
foreach ($array as $key => $value) {
if (is_array($value)) {
if (!isset($tableHeader)) {
$tableHeader =
'<th>' .
implode('</th><th>', array_keys($value)) .
'</th>';
}
array_keys($value);
$out .= '<tr>';
$out .= array2Html($value, false);
$out .= '</tr>';
} else {
$out .= "<td>".htmlspecialchars($value)."</td>";
}
}
if ($table) {
return '<table>' . $tableHeader . $out . '</table>';
} else {
return $out;
}
}
However, your table headers have to be a part of the array, which is pretty common when it comes from a database. e.g.
$shop = array(
array(
'title' => 'rose',
'price' => 1.25,
'number' => 15,
),
array(
'title' => 'daisy',
'price' => 0.75,
'number' => 25,
),
array(
'title' => 'orchid',
'price' => 1.15,
'number' => 7,
),
);
print array2Html($shop);
Hope it helps ;)
Build two foreach loops and iterate through your array.
Print out the value and add HTML table tags around that.
You may use this function. To add table header you can setup a second parameter $myTableArrayHeader and do the same with the header information in front of the body:
function insertTable($myTableArrayBody) {
$x = 0;
$y = 0;
$seTableStr = '<table><tbody>';
while (isset($myTableArrayBody[$y][$x])) {
$seTableStr .= '<tr>';
while (isset($myTableArrayBody[$y][$x])) {
$seTableStr .= '<td>' . $myTableArrayBody[$y][$x] . '</td>';
$x++;
}
$seTableStr .= '</tr>';
$x = 0;
$y++;
}
$seTableStr .= '</tbody></table>';
return $seTableStr;
}
PHP code:
$multiarray = array (
array("name"=>"Argishti", "surname"=>"Yeghiazaryan"),
array("name"=>"Armen", "surname"=>"Mkhitaryan"),
array("name"=>"Arshak", "surname"=>"Aghabekyan"),
);
$count = 0;
foreach ($multiarray as $arrays){
$count++;
echo "<table>" ;
echo "<span>table $count</span>";
echo "<tr>";
foreach ($arrays as $names => $surnames){
echo "<th>$names</th>";
echo "<td>$surnames</td>";
}
echo "</tr>";
echo "</table>";
}
CSS:
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;``
}
I had a similar need, but my array could contain key/value or key/array or array of arrays, like this array:
$array = array(
"ni" => "00000000000000",
"situacaoCadastral" => array(
"codigo" => 2,
"data" => "0000-00-00",
"motivo" => "",
),
"naturezaJuridica" => array(
"codigo" => "0000",
"descricao" => "Lorem ipsum dolor sit amet, consectetur",
),
"dataAbertura" => "0000-00-00",
"cnaePrincipal" => array(
"codigo" => "0000000",
"descricao" => "Lorem ips",
),
"endereco" => array(
"tipoLogradouro" => "Lor",
"logradouro" => "Lorem i",
"numero" => "0000",
"complemento" => "",
"cep" => "00000000",
"bairro" => "Lorem ",
"municipio" => array(
"codigo" => "0000",
"descricao" => "Lorem ip",
),
),
"uf" => "MS",
"pais" => array(
"codigo" => "105",
"descricao" => "BRASIL",
),
"municipioJurisdicao" => array(
"codigo" => "0000000",
"descricao" => "DOURADOS",
),
"telefones" => array(
array(
'ddd' => '67',
'numero' => '00000000',
),
),
"correioEletronico" => "lorem#ipsum-dolor-sit.amet",
"capitalSocial" => 0,
"porte" => "00",
"situacaoEspecial" => "",
"dataSituacaoEspecial" => ""
);
The function I created to solve was:
function array_to_table($arr, $first=true, $sub_arr=false){
$width = ($sub_arr) ? 'width="100%"' : '' ;
$table = ($first) ? '<table align="center" '.$width.' bgcolor="#FFFFFF" border="1px solid">' : '';
$rows = array();
foreach ($arr as $key => $value):
$value_type = gettype($value);
switch ($value_type) {
case 'string':
$val = (in_array($value, array(""))) ? " " : $value;
$rows[] = "<tr><td><strong>{$key}</strong></td><td>{$val}</td></tr>";
break;
case 'integer':
$val = (in_array($value, array(""))) ? " " : $value;
$rows[] = "<tr><td><strong>{$key}</strong></td><td>{$value}</td></tr>";
break;
case 'array':
if (gettype($key) == "integer"):
$rows[] = array_to_table($value, false);
elseif(gettype($key) == "string"):
$rows[] = "<tr><td><strong>{$key}</strong></td><td>".
array_to_table($value, true, true) . "</td>";
endif;
break;
default:
# code...
break;
}
endforeach;
$ROWS = implode("\n", $rows);
$table .= ($first) ? $ROWS . '</table>' : $ROWS;
return $table;
}
echo array_to_table($array);
And the output is this
<?php
echo "<table>
<tr>
<th>title</th>
<th>price</th>
<th>number</th>
</tr>";
for ($i=0; $i<count($shop, 0); $i++)
{
echo '<tr>';
for ($j=0; $j<3; $j++)
{
echo '<td>'.$shop[$i][$j].'</td>';
}
echo '</tr>';
}
echo '</table>';
You can optimize it, but that should do.
You can use foreach to iterate the array $shop and get one of the arrays with each iteration to echo its values like this:
echo '<table>';
echo '<thead><tr><th>title</td><td>price</td><td>number</td></tr></thead>';
foreach ($shop as $item) {
echo '<tr>';
echo '<td>'.$item[0].'</td>';
echo '<td>'.$item[1].'</td>';
echo '<td>'.$item[2].'</td>';
echo '</tr>';
}
echo '</table>';
this will print 2-dimensional array as table.
First row will be header.
function array_to_table($table)
{
echo "<table>";
// Table header
foreach ($table[0] as $header) {
echo "<th>".$header."</th>";
}
// Table body
$body = array_slice( $table, 1, null, true);
foreach ($body as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>".$cell."</td>";
}
echo "</tr>";
}
echo "</table>";
}
usage:
arrayOfArrays = array(
array('header1',"header2","header3"),
array('1.1','1.2','1.3'),
array('2.1','2.2','2.3'),
);
array_to_table($arrayOfArrays);
result:
<table><tbody><tr><th>header1</th><th>header2</th><th>header3/th><tr><td>1.1</td><td>1.2</td><td>1.3</td></tr><tr><td>2.1</td><td>2.2</td><td>2.3</td></tr><tr><td>3.1</td><td>3.2</td><td>3.3</td></tr></tbody></table>
Array into table.
Array into div.
JSON into table.
JSON into div.
All are nicely handle this class. Click here to get a class
How to use it?
Just get and object
$obj = new Arrayinto();
Create an array you want to convert
$obj->array_object = array("AAA" => "1111",
"BBB" => "2222",
"CCC" => array("CCC-1" => "123",
"CCC-2" => array("CCC-2222-A" => "CA2",
"CCC-2222=B" => "CB2"
)
)
);
If you want to convert Array into table. Call this.
$result = $obj->process_table();
If you want to convert Array into div. Call this.
$result = $obj->process_div();
Let suppose if you have a JSON
$obj->json_string = '{
"AAA":"11111",
"BBB":"22222",
"CCC":[
{
"CCC-1":"123"
},
{
"CCC-2":"456"
}
]
}
';
You can convert into table/div like this
$result = $obj->process_json('div');
OR
$result = $obj->process_json('table');
Here is the more generic version of #GhostInTheSecureShell 's answer.
<?php
function build_tabular_format($items)
{
$html = '';
$items_chunk_array = array_chunk($items, 4);
foreach ($items_chunk_array as $items_single_chunk)
{
$html .= '<div class="flex-container">';
foreach ($items_single_chunk as $item)
{
$html .= '<div class="column-3">';
$html .= $item['fields']['id'];
$html .= '</div>';
}
$html .= '</div>';
}
return $html;
}
$items = array(
array(
'fields' => array(
'id' => '1',
) ,
) ,
array(
'fields' => array(
'id' => '2',
) ,
) ,
array(
'fields' => array(
'id' => '3',
) ,
) ,
array(
'fields' => array(
'id' => '4',
) ,
) ,
array(
'fields' => array(
'id' => '5',
) ,
) ,
array(
'fields' => array(
'id' => '6',
) ,
) ,
array(
'fields' => array(
'id' => '7',
) ,
) ,
array(
'fields' => array(
'id' => '8',
) ,
) ,
);
echo build_tabular_format($items);
?>
The output will be like:
<div class="flex-container">
<div class="column-3">1</div>
<div class="column-3">2</div>
<div class="column-3">3</div>
<div class="column-3">4</div>
</div>
<div class="flex-container">
<div class="column-3">5</div>
<div class="column-3">6</div>
<div class="column-3">7</div>
<div class="column-3">8</div>
</div>