Build table from two different array results mixing values - php

I have this two arrays:
$pax = [
'person1',
'person2
];
$prices = [
[
'price1' => 100,
'price2' => 200,
'price3' => 300
],
[
'price1' => 100,
'price2' => 200,
'price3' => 300
]
];
I want to create a table like this from the previous values:
<table style="width:100%">
<tr>
<th>Description</th>
<th>person1</th>
<th>person2</th>
<th>Total</th>
</tr>
<tr>
<td>price1</td>
<td>$100</td>
<td>$100</td>
<td>$200</td>
</tr>
<tr>
<td>price2</td>
<td>$200</td>
<td>$200</td>
<td>$400</td>
</tr>
<tr>
<td>price3</td>
<td>$300</td>
<td>$300</td>
<td>$600</td>
</tr>
</table>
But I can't get it to work with this code:
$pax = ['person1', 'person2'];
$prices = [
[
'price1' => 100,
'price2' => 200,
'price3' => 300
],
[
'price1' => 100,
'price2' => 200,
'price3' => 300
]
];
$table = '<table width="100%"><thead><tr><th>Price Key</th>';
foreach ($pax as $person) {
$table .= "<th>$person</th>";
}
$table .= '<th>Total</th></thead><tbody>';
foreach ($pax as $idx => $person) {
$table .= '<tr>';
foreach ($prices[$idx] as $key => $value) {
$table .= "<td>$key</td>";
$table .= "<td>$value</td>";
$table .= '<td>Total</td>';
}
$table .= '<tr>';
}
$table .= '</tbody></table>';
What I am missing here?

Your second loop is inside out. Each row is for a different priceX, but you have a row for each element of the $pax array.
You also need to calculate the totals.
if (!empty($prices)) { // So we don't try to access $prices[0] on empty array
foreach (array_keys($prices[0]) as $key) {
echo "<td>$key</td>";
$total = 0;
foreach ($prices as $person) {
$total += $person[$key];
echo "<td>\${$person[$key]}</td>";
}
echo "<td>\$$total</td>";
}
}

You are almost there. But you have some issues in your second for loop.
Try this:
foreach (array_keys($prices[0]) as $key) {
echo "<td>$key</td>";
$total = 0;
foreach ($prices as $price) {
echo "<td>\${$price[$key]}</td>";
$total += $price[$key];
}
echo "<td>\$$total</td>";
}

Related

How to draw a table with data from Mysql?

I have obtained the following data through Mysql.
idx item_name parent_id
44 'A' -1
46 'B' -1
47 'C' 44
48 'D' 44
49 'E' 44
50 'F' 46
51 'G' 47
52 'H' 47
53 'I' 48
I want to draw a table using this data.
I've searched for information, but it's very difficult.
Is there anyone who can help me?
Example
<table>
<thead>
<tr>
<th>item1</th>
<th>item2</th>
<th>item3</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="4">A</td>
<td rowspan="2">C</td>
<td>G</td>
<td>-</td>
</tr>
<tr>
<td>H</td>
<td>-</td>
</tr>
<tr>
<td>D</td>
<td>I</td>
<td>-</td>
</tr>
<tr>
<td>E</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>B</td>
<td>F</td>
<td>-</td>
<td>-</td>
</tr>
</tbody>
Is there a PHP library related to this?
=========================================
The values in the database consist of a passenger structure. (Parent ID Existence)
I want to make this data into a table using PHP.
"Rowspan" will be used to accommodate the number of children.
However, this method of HTML coding is very difficult.
I need a library or a related example code.
Here you go, the code that I made to solve your problem.
It is not perfect but I hope you got the idea.
Your problem cannot be solved by a simple array loop, because your data is not a simple table but a tree. Therefore, using recursive loop to walk through the data is one of the solutions.
<?php
// the data, should be obtained from your database
// to simplify the code, I made them into an array of objects
$rows[] = (object) array( 'idx' => 44, 'name' => 'A', 'pid' => -1 );
$rows[] = (object) array( 'idx' => 46, 'name' => 'B', 'pid' => -1 );
$rows[] = (object) array( 'idx' => 47, 'name' => 'C', 'pid' => 44 );
$rows[] = (object) array( 'idx' => 48, 'name' => 'D', 'pid' => 44 );
$rows[] = (object) array( 'idx' => 49, 'name' => 'E', 'pid' => 44 );
$rows[] = (object) array( 'idx' => 50, 'name' => 'F', 'pid' => 46 );
$rows[] = (object) array( 'idx' => 51, 'name' => 'G', 'pid' => 47 );
$rows[] = (object) array( 'idx' => 52, 'name' => 'H', 'pid' => 47 );
$rows[] = (object) array( 'idx' => 53, 'name' => 'I', 'pid' => 48 );
// Build Tree
foreach($rows as $r) {
$r->child = [];
foreach($rows as $c) {
if($r->idx == $c->idx) continue;
if($c->pid == $r->idx)
$r->child[] = $c;
}
}
// recursive walk through the trees to set maxLevel and nodeLevel
function cLeaves($node, $level, &$maxLevel) {
$count = 0;
if(count($node->child) == 0) {
$node->span = 1;
$node->level = $level;
$maxLevel = $maxLevel < $level ? $level : $maxLevel;
return 1;
} else {
$node->level = $level;
$level++;
foreach($node->child as $c) {
$count += cLeaves($c, $level, $maxLevel);
}
$node->span = $count;
return $count;
}
}
// recursive walk through the trees to draw table
function drawTable($cnode, $maxLevel) {
echo '<td rowspan="'.$cnode->span.'">'.$cnode->name.'</td>';
if(count($cnode->child) == 0) {
if($cnode->level < $maxLevel) {
for($i = $cnode->level; $i<$maxLevel; $i++)
echo '<td>-</td>';
}
echo '<td>-</td>'; // for the value column
echo '</tr>';
return;
}
foreach($cnode->child as $c) {
drawTable($c, $maxLevel);
}
}
// update the data structure
$maxLevel = 0;
foreach($rows as $r) {
if($r->pid == -1) {
$level = 0;
$r->span = cLeaves($r, $level, $maxLevel);
$r->level = $level;
}
}
echo '<table border="1">';
echo '<tr>';
// draw table's title row
for($i = 0; $i <= $maxLevel; $i++) {
echo '<td>item'.($i+1).'</td>';
if($i == $maxLevel) echo '<td>value</td>';
}
echo '</tr>';
// draw tree on table format
foreach($rows as $r) {
if($r->pid == -1) {
echo '<tr>';
drawTable($r, $maxLevel);
}
}
echo '</table>';
?>
If you run the code, the result would be something like below:
What I still remember from PHP is, you can use for loop and put one of these rows into the php <tag>. Then use your SELECT query to get each tuple from MySql into each tuple's cells in this tag:
<tr>
<td> Cell value using Sql Select statement</td>
<td> Cell value using Sql Select statement</td>
<td> Cell value using Sql Select statement</td>
</tr>
You can do this process n of times depend on the No. Of rows you want to insert into the table.
Then, close your **PHP <tag>.
you can use mysqli_fetch_assoc to fetch your data from the database and run a loop to format it using html table:
<table border=1>
<thead>
<tr>
<th>idx</th>
<th>item_name</th>
<th>parent_id</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("localhost", "root", "", "yourdatabase");
$table = mysqli_query($con, "SELECT idx, item_name, parent_id FROM mytable");
while ($record = mysqli_fetch_assoc($table)) {
echo "<tr>";
echo "<td>" . $record["idx"] . "</td>";
echo "<td>" . $record["item_name"] . "</td>";
echo "<td>" . $record["parent_id"] . "</td>";
echo "</tr>";
}
?>
</tbody>
If you want to use a library, you can check codeigniter (PHP framework)'s table helper.
https://codeigniter.com/userguide3/libraries/table.html
$this->table->generate($table);

php dynamic table from muldimentional array

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
)
)

keys and values of dynamically generated array

i have an array:
Array
(
[0] => Array
(
[Dated] => 2017-04-01
[Nadeem] => 1995
[NadeemKaat] => 40
[Ali] => 0
[AliKaat] => 0
[Usman] => 0
[UsmanKaat] => 0
)
[1] => Array
(
[Dated] => 2017-04-06
[Nadeem] => 0
[NadeemKaat] => 0
[Ali] => 4800
[AliKaat] => 96
[Usman] => 0
[UsmanKaat] => 0
)
[2] => Array
(
[Dated] => 2017-04-20
[Nadeem] => 0
[NadeemKaat] => 0
[Ali] => 0
[AliKaat] => 0
[Usman] => 2100
[UsmanKaat] => 42
)
)
i want to print out this array values like this:
Date | Nadeem | Ali | Usman
2017-04-01 | 1995 | |
2017-04-06 | | 4800 |
2017-04-20 | | |2100
i am confuse here how to handle this kind of array, please help me out
i am trying with simply foreach loop
foreach ($stock as $key => $value)
{
echo $key . $value;
}
Try this:
if (!empty($stock)) {
echo '<table><tr>';
foreach ($stock[0] as $key => $value)
{
echo '<th>' . $key . '</th>';
}
echo '</tr>';
foreach ($stock as $value)
{
echo '<tr>';
foreach ($value as $key2 => $field) {
echo '<td>' . $field . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
#Shafat Ahmad try this below one:
<?php
$stock = array(
array(
"Dated" => "2017-04-01",
"Nadeem" => 1995,
"NadeemKaat" => 40,
"Ali" => 0,
"AliKaat" => 0,
"Usman" => 0,
"UsmanKaat" => 0
),
array(
"Dated" => "2017-04-06",
"Nadeem" => 0,
"NadeemKaat" => 0,
"Ali" => 4800,
"AliKaat" => 96,
"Usman" => 0,
"UsmanKaat" => 0
),
array(
"Dated" => "2017-04-20",
"Nadeem" => 0,
"NadeemKaat" => 0,
"Ali" => 0,
"AliKaat" => 0,
"Usman" => 2100,
"UsmanKaat" => 42
)
);
?>
<table align="center" border="1">
<tr>
<th>Date</th>
<th>Nadeem</th>
<th>Ali</th>
<th>Usman</th>
</tr>
<?php
foreach ($stock as $value) {
?><tr>
<th><?php echo $value["Dated"] ?></th>
<th><?php echo $value["Nadeem"] ?></th>
<th><?php echo $value["Ali"] ?></th>
<th><?php echo $value["Usman"] ?></th>
</tr><?php
}
Try inner loops
// print header
foreach ($stock[0] as $key => $value) {
echo $key. ' | '
}
// print data
foreach ($stock as $item)
{
foreach ($item as $value) {
echo $value . ' | '
}
}
And then do a little bit play with changing | with <tr>, <td> and so on if you want proper table.
Or you can use
$header = array_keys($stock[0]);
echo '<table><tr><th>';
echo implode('</th><th>', $header);
echo '</th></tr>';
// print data
foreach ($stock as $item) {
echo '<tr><td>';
echo implode('</td><td>', $item);
echo '</td></tr>';
}
echo '</table>';
Try this:
foreach($stock as $data) {
echo $data['Dated'].' | '.($data['Nadeem'] ? $data['Nadeem'] : "") .' | '.$data['NadeemKaat'].' | '.$data['Ali'].' | '.$data['AliKaat'].' | '.$data['Usman'].' | '.$data['UsmanKaat'].'<br>';
}
Here is sample program. Maybe it'll help you.
// user data can be dynamic
$userData = array('Nadeem', 'Ali', 'Usman');
// tblRows data can also be dynamic
$tblRowsData = array(
'2017-04-01' => array('Nadeem'=>1995, 'Ali'=>'', 'Usman'=>''),
'2017-04-06' => array('Nadeem'=>'', 'Ali'=>4800, 'Usman'=>''),
'2017-04-20' => array('Nadeem'=>'', 'Ali'=>'', 'Usman'=>2100)
);
echo "<table border=1>";
echo "<tr>";
echo "<td>Date</td>";
foreach ($userData as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
foreach ($tblRowsData as $key => $value) {
echo "<tr>";
echo "<td>$key</td>";
foreach ($userData as $key1 => $value1) {
echo "<td>".$value[$value1]."</td>";
}
echo "</tr>";
}
echo "</table>";
$keys = array_keys($some[0]);
$theader = implode("\t", $keys);
echo $theader;
foreach ($some as $one) {
echo "\n";
for ($i = 0; $i < count($keys); $i++) {
echo $one[$keys[$i]] . "\t";
}
}
Assuming structure of your data doesn't change and $some is your given above array
Output :
Dated Nadeem NadeemKaat Ali AliKaat Usman UsmanKaat
2017-04-01 1995 40 0 0 0 0
2017-04-06 0 0 4800 96 0 0
2017-04-20 0 0 0 0 2100 42
A bit shit coded, fast written solution)))
$data = [];
foreach($input as $value) {
foreach($value as $person => $count) {
if($person !== 'Dated') {
$data[$value['Dated']][$person] = $count;
}
}
}
if(!$data) {
die('empty');
}
$persons = array_keys(reset($data));
$html = '<table border="1"><thead>
<th>Date</th>';
foreach($persons as $key) {
$html .= "<th>{$key}</th>";
}
$html .= '</thead><tbody>';
while($temp = array_splice( $data, 0, 1 )) {
$date = array_keys($temp)[0];
$html .= "<tr><td>".$date."</td>";
foreach($persons as $name) {
$val = isset($temp[$date][$name]) ? $temp[$date][$name] : '-';
$html .= "<td>".$val."</td>";
}
$html .= "</tr>";
}
$html .= '</tbody></table>';
die($html);
Where input like
$input = [
[
'Dated' => '2017-04-01',
'Nadeem' => 1995,
'NadeemKaat' => 40,
'Ali' => 0,
'AliKaat' => 0,
'Usman' => 0,
'UsmanKaat' => 0
],
[
'Dated' => '2017-05-11',
'Nadeem' => 123,
'NadeemKaat' => 40,
'Ali' => 3,
'AliKaat' => 0,
'Usman' => 0,
'UsmanKaat' => 0
]
];
Output in HTML:

Passing arrays as URL parameter with combinations

I'm kinda stucked here.
I'm trying to build URL for product variants like:
&brand=6&color=11,12,etc
So how can I combine the keys of array into one string like above
Also If you could suggest me another way to achieve the desired result.
Thank you very much!
You first have to combine the values of "brand" with the values of "color". Afterwards, you can output them together:
<?php
$columns = [
'brand' => [
['b1A', 'b1B'],
['b2A', 'b2B'],
],
'color' => [
['c1A', 'c1B'],
['c2A', 'c2B'],
],
];
$data = [];
foreach ($columns as $title => $rows) {
foreach ($rows as $id => $values) {
if (!isset($data[$id])) {
$data[$id] = [];
}
$data[$id][$title] = $values;
}
}
foreach ($data as $row) {
$output = '';
foreach ($row as $key => $values) {
$output .= '&' . $key . '=' . implode(',', $values);
}
echo $output . '<br/>' . PHP_EOL;
}
<?php
$filters = [
"brand" => [
1 => "Adidas",
2 => "Puma"
],
"color" => [
1 => "White",
2 => "Blue",
3 => "Red",
4 => "Yellow"
]
];
foreach($filters['brand'] as $key => $val){
foreach($filters['color'] as $k => $v){
echo "brand=$key,$val&color=$k,$v" . PHP_EOL;
echo "brand=$val&color=$v" . PHP_EOL;
}
}
Output
brand=1,Adidas&color=1,White
brand=Adidas&color=White
...
Example 2;
foreach($filters['brand'] as $key => $val){
echo "&brand=$key,$val&color=" . implode(',',$filters['color']) . PHP_EOL;
}
&brand=1,Adidas&color=White,Blue,Red,Yellow
&brand=2,Puma&color=White,Blue,Red,Yellow

How to create a HTML Table from a PHP array?

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>

Categories