After trying some methods without success, I must give up, and ask this here.
So I have an array $product_var_tpl_list = array(); the output looks like this:
Shop1m | Pruduct 12
Shop1m | Product 366
Shop1m | Product 66
Shop3a | Product 89
Shop3a | Product 5
Shop55 | Product 6
I want to avoid dublicating strings from column 1 - the output must be like this:
Shop1m | Pruduct 12
| Product 366
| Product 66
Shop3a | Product 89
| Product 5
Shop55 | Product 6
The PHP code is:
$product_var_tpl_list = array();
foreach ($order->product_list as $product) {
$price = Product::getPriceStatic((int)$product['id_product'], false, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 6, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$price_wt = Product::getPriceStatic((int)$product['id_product'], true, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 2, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$product_price = Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt;
//here is data about the seller
$idProduct = (int)$product['id_product'];
$SellerInfoOverride = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'wk_mp_seller_product` WHERE `id_ps_product` = '.(int) $idProduct);
foreach ($SellerInfoOverride as $key => $value) {
$sellerid = $value['id_seller'];
//$seller = $mpSeller->getSeller($value['id_seller'], $this->context->language->id);
$SellerInfoDetails = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'wk_mp_seller` WHERE `id_seller` = '.(int) $sellerid);
foreach ($SellerInfoDetails as $key => $value) {
$seller_name = $value['shop_name_unique'];
}
}
$product_var_tpl = array(
'reference' => $seller_name,
'name' => $product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : ''),
'unit_price' => Tools::displayPrice($product_price, $this->context->currency, false),
'price' => Tools::displayPrice($product_price * $product['quantity'], $this->context->currency, false),
'quantity' => $product['quantity'],
'customization' => array()
);
$customized_datas = Product::getAllCustomizedDatas((int)$order->id_cart);
if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
$product_var_tpl['customization'] = array();
foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
$customization_text = '';
if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
$customization_text .= $text['name'].': '.$text['value'].'<br />';
}
}
if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
$customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])).'<br />';
}
$customization_quantity = (int)$product['customization_quantity'];
$product_var_tpl['customization'][] = array(
'customization_text' => $customization_text,
'customization_quantity' => $customization_quantity,
'quantity' => Tools::displayPrice($customization_quantity * $product_price, $this->context->currency, false)
);
}
}
$product_var_tpl_list[] = $product_var_tpl;
// Check if is not a virutal product for the displaying of shipping
if (!$product['is_virtual']) {
$virtual_product &= false;
}
} // end foreach ($products)
// this will sort the output by alphabetical order based on reference value
usort($product_var_tpl_list, function($a, $b) {
return strcmp($a['reference'], $b['reference']);
});
As the comments have pointed out above, there are a few pieces of your question that are a bit vague, mainly the structure of your array data. Because of this, I've made some assumptions in my answer below. Note that while it works, you may need to modify it slightly to fit your particular use case:
/*
* Original Data
*/
$data = [
[ "key" => "Shop1m", "value" => "Product 12" ],
[ "key" => "Shop1m", "value" => "Product 366" ],
[ "key" => "Shop1m", "value" => "Product 66" ],
[ "key" => "Shop3a", "value" => "Product 89" ],
[ "key" => "Shop3a", "value" => "Product 5" ],
[ "key" => "Shop55", "value" => "Product 6" ]
];
/*
* Let's organize the data more like you'd like the output
* to be. We'll bring the initial keys to the forefront by
* creating a multi-dimensional array where all of the
* related products are grouped under their appropriate
* key header.
*/
$altered_data = [];
foreach($data as $entry) {
if(!isset($altered_data[$entry["key"]])) {
$altered_data[$entry["key"]] = [];
}
$altered_data[$entry["key"]][] = $entry["value"];
}
/*
* Now we'll output the data. This becomes trivial with a
* double "for" loop (i.e. "foreach" + "for" loops) without
* the need for keeping track of the previous header.
*/
echo "<table><tbody>";
foreach($altered_data as $key => $value) {
for($a = 0, $len = count($value); $a < $len; $a++) {
echo "<tr>";
echo (0 === $a) ? "<td>" . $key . "</td>" : "<td></td>";
echo "<td>" . $value[$a] . "</td>";
}
}
echo "</tbody></table>";
My answer will be generic.
You've an array with reference, name columns, where reference is shop.
Group them:
$sellerProducts = [];
foreach($product_var_tpl AS $product) :
if (!isset($sellerProducts[$product['reference']])) {
$sellerProducts[$product['reference']] = [];
}
$sellerProducts[$product['reference']][] = $product;
endforeach;
$smarty->assign('sellerProducts', $sellerProducts);
and then output it:
foreach($sellerProducts AS $seller => $products) :
print($seller.":\n");
foreach($products AS $product) :
print($product['name']."\n");
endforeach;
print("\n\n");
endforeach;
OR Smarty template example (foreach manual):
<table>
<thead>
<th>Seller</th>
<th>Product name</th>
</thead>
<tbody>
{foreach from=$sellerProducts key=$seller item=$products}
<tr>
<td>{$seller}</td>
<td>
<ol>
{foreach from=$products item=$product}
<li>{$product.name}</li>
{/foreach}
</ol>
</td>
</tr>
{/foreach}
</tbody>
</table>
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>";
}
I'm looking to modify a table on a page to include merged rows.
Here is the php code that deals with the output from a mysql db:
######## PRINT OUT TABLE WITH YEARS AND OFFICES PLUS NAMES IN CELLS ########
for ($y = $year_max; $y >=$year_min; $y--){
echo '<tr><th>'.$y.'</th>';
for ($i = 0; $i<count($offices_used); $i++){
if (isset($data[$y][$offices_used[$i]])){
echo '<td>'.$data[$y][$offices_used[$i]].'</td>';
} // END IF
else {
echo '<td></td>';
} // END ELSE
} echo '</tr>';
} // END FOR
The table further below is generated from a multidimensional array such as immediately below;
array (
[2013] => Array
(
[President] => John Mills
[Internal VP] => Virgil Bagdonas
[External VP] => Reid Gilmore
[Treasurer] => Todd Heino
[Secretary] => Eric Holmquist
[Newsletter] => Art Bodwell
[Webmaster] => Dave Eaton
[Photographer] => Rick Angus
[Video Librarian] => Mike Peters
[Store Manager] => Kevin Nee
)
[2012] => Array
(
[President] => Dave Eaton
[Internal VP] => Jim Metcalf
[External VP] => Reid Gilmore
[Treasurer] => Mike Peters
[Secretary] => Eric Holmquist
[Newsletter] => Art Bodwell
[Webmaster] => Dave Eaton
[Photographer] => Peter Wilcox
[Video Librarian] => Ray Asselin
[Store Manager] => Joe Giroux
)
[2011] => Array
(
[President] => Charlie Croteau
[Internal VP] => Reid Gilmore
[External VP] => Rick Angus
[Treasurer] => Mike Peters
[Secretary] => Eric Holmquist
[Newsletter] => Ron Rocheleau
[Webmaster] => Dave Eaton
[Photographer] => Peter Wilcox
[Video Librarian] => Ray Asselin
[Book Librarian] => Roger Boisvert
[Store Manager] => Mike Smith
)
...etc
My php code NOW generates this table from mysql db:
<tr>
<th>Year</th>
<th>President</th>
<th>Internal VP</th>
<th>External VP</th>
<th>Treasurer</th>
<th>Secretary</th>
<th>Webmaster</th>
<th>Newsletter</th>
<th>Photographer</th>
<th>Video Librarian</th>
<th>Book Librarian</th>
<th>Store Manager</th>
</tr>
<tr>
<th>2013</th>
<td>John Mills</td>
<td>Virgil Bagdonas</td>
<td>Reid Gilmore</td>
<td>Todd Heino</td>
<td>Eric Holmquist</td>
<td>Dave Eaton</td>
<td>Art Bodwell</td>
<td>Rick Angus</td>
<td>Mike Peters</td>
<td></td>
<td>Kevin Nee</td>
</tr>
<tr>
<th>2012</th>
<td>Dave Eaton</td>
<td>Jim Metcalf</td>
<td>Reid Gilmore</td>
<td>Mike Peters</td>
<td>Eric Holmquist</td>
<td>Dave Eaton</td>
<td>Art Bodwell</td>
<td>Peter Wilcox</td>
<td>Ray Asselin</td>
<td></td>
<td>Joe Giroux</td>
</tr>
<tr>
<th>2011</th>
<td>Charlie Croteau</td>
<td>Reid Gilmore</td>
<td>Rick Angus</td>
<td>Mike Peters</td>
<td>Eric Holmquist</td>
<td>Dave Eaton</td>
<td>Ron Rocheleau</td>
<td>Peter Wilcox</td>
<td>Ray Asselin</td>
<td>Roger Boisvert</td>
<td>Mike Smith</td>
</tr>
But I WOULD LIKE to modify the array handling output to get the following:
<tr>
<th>Year</th>
<th>President</th>
<th>Internal VP</th>
<th>External VP</th>
<th>Treasurer</th>
<th>Secretary</th>
<th>Webmaster</th>
<th>Newsletter</th>
<th>Photographer</th>
<th>Video Librarian</th>
<th>Book Librarian</th>
<th>Store Manager</th>
</tr>
<tr>
<th>2013</th>
<td>John Mills</td>
<td>Virgil Bagdonas</td>
<td rowspan= "3">Reid Gilmore</td>
<td>Todd Heino</td>
<td rowspan="3">Eric Holmquist</td>
<td rowspan="9">Dave Eaton</td>
<td rowspan="2">Art Bodwell</td>
<td>Rick Angus</td>
<td>Mike Peters</td>
<td></td>
<td>Kevin Nee</td>
</tr>
<tr>
<th>2012</th>
<td>Dave Eaton</td>
<td>Jim Metcalf</td>
<td rowspan="2">Mike Peters</td>
<td>Peter Wilcox</td>
<td rowspan="3">Ray Asselin</td>
<td></td>
<td>Joe Giroux</td>
</tr>
<tr>
<th>2011</th>
<td>Charlie Croteau</td>
<td>Rick Angus</td>
<td>Ron Rocheleau</td>
<td>Peter Wilcox</td>
<td>Roger Boisvert</td>
<td>Mike Smith</td>
</tr>
Any leads on how to add a flag or counter to accomplish this is welcome. Thanks!
try this hope to work.(because I have not run it but think should work).
CODE for colspan:
for ($y = $year_max; $y >=$year_min; $y--){
echo '<tr><th>'.$y.'</th>';
$lastVal='';
$buf=array();
for ($i = 0; $i<count($offices_used); $i++){
(!isset($data[$y][$offices_used[$i]])?($data[$y][$offices_used[$i]]=''):'');// Im not sure that is really needed
if($lastVal==$data[$y][$offices_used[$i]]){
$buf[count($buf)-1]['rep']++;
}else{
$lastVal=$data[$y][$offices_used[$i]];
$buf[]=array('data'=>$lastVal,'rep'=>1);
}
foreach($buf as $arr){
echo '<td'.($arr['rep']>1?' colspan="'.$arr['rep'].'"':'') . '>'.$arr['data'].'</td>';
}
} echo '</tr>';
} // END FOR
NOTICE: error of code corrected
CODE for rowspan:(I think it can be down easier than this. bur I have tried to be good).
$buf=array();
for ($i = 0; $i<count($offices_used); $i++){// this loop makes fill $buf
$lastVal='';
for ($y = $year_max; $y >=$year_min; $y--){
(!isset($data[$y][$offices_used[$i]])?($data[$y][$offices_used[$i]]=''):'');// Im not sure that is really needed
if($lastVal==$data[$y][$offices_used[$i]]){
$buf[$i][count($buf[$i])-1]['rep']++;
}else{
$lastVal=$data[$y][$offices_used[$i]];
$buf[$i][$year_max-$y]=array('data'=>$lastVal,'rep'=>1);
}
}
}
$mtemp=$year_max;
foreach($buf as $row){
echo '<tr><th>'.$mtemp.'</th>';
foreach($row as $rec){
echo '<td'.($rec['rep']>1?' rowspan="'.$rec['rep'].'"':'') . '>'.$rec['data'].'</td>';
}
$mtemp--;
echo '</tr>';
}
really hope to work.
NOTICE: corrected
Solved by using:
############################################################################
######## PRINT OUT TABLE WITH YEARS AND OFFICES PLUS NAMES IN CELLS ########
for ($y = $year_max; $y >=$year_min; $y--){ // Loop through years
echo '<tr><th>'.$y.'</th>';
for ($i = 0; $i<count($offices_used); $i++){
if (isset($data[$y][$offices_used[$i]])){
$rowz =1;
if(!($data[$y][$offices_used[$i]] == $data[($y+1)][$offices_used[$i]])){
while ($data[$y][$offices_used[$i]] == $data[($y-$rowz)][$offices_used[$i]]) $rowz ++;
echo '<td rowspan = "'.$rowz.'">'.$data[$y][$offices_used[$i]].'</td>';
}
} // END IF
else {
echo '<td align = "center"> - </td>';
} // END ELSE
} echo '</tr>'; // End row of current year
} // END FOR Loop through years
echo '</table>';
See http://jsfiddle.net/eaton9999/8gMVK/ for resultant output page.
Thanks again to imsiso and other who helped!
I wrote a library a few days ago that can handle this stuff..
Have a look at https://github.com/donquixote/cellbrush
The benefit of the library is that you don't need to think about the order of cells in html, and which cells need to be skipped due to rowspan or colspan. Instead, you can just "paint" a cell anywhere in the grid, with whichever rowspan or colspan you want. And instead of specifying a number for rowspan or colspan, you simply specify the first and last row and column names of the rospan/colspan region.
E.g.
$table->td(['2011', '2013'], 'Secretary', 'Eric Holmquist');
Below is some code that creates the table you were asking for, with the help of this library. You still need some logic to calculate the intervals, but at least you don't need to worry about the integrity of the table html.
(This question is quite old, but there might still be people running into it from Google. So I hope it might be useful.)
<?php
require_once __DIR__ . '/vendor/autoload.php';
$data = array(
'2013' => array(
'President' => 'John Mills',
'Internal VP' => 'Virgil Bagdonas',
'External VP' => 'Reid Gilmore',
'Treasurer' => 'Todd Heino',
'Secretary' => 'Eric Holmquist',
'Newsletter' => 'Art Bodwell',
'Webmaster' => 'Dave Eaton',
'Photographer' => 'Rick Angus',
'Video Librarian' => 'Mike Peters',
'Store Manager' => 'Kevin Nee',
),
'2012' => array(
'President' => 'Dave Eaton',
'Internal VP' => 'Jim Metcalf',
'External VP' => 'Reid Gilmore',
'Treasurer' => 'Mike Peters',
'Secretary' => 'Eric Holmquist',
'Newsletter' => 'Art Bodwell',
'Webmaster' => 'Dave Eaton',
'Photographer' => 'Peter Wilcox',
'Video Librarian' => 'Ray Asselin',
'Store Manager' => 'Joe Giroux',
),
'2011' => array(
'President' => 'Charlie Croteau',
'Internal VP' => 'Reid Gilmore',
'External VP' => 'Rick Angus',
'Treasurer' => 'Mike Peters',
'Secretary' => 'Eric Holmquist',
'Newsletter' => 'Ron Rocheleau',
'Webmaster' => 'Dave Eaton',
'Photographer' => 'Peter Wilcox',
'Video Librarian' => 'Ray Asselin',
'Book Librarian' => 'Roger Boisvert',
'Store Manager' => 'Mike Smith',
),
);
// Collect positions to build table columns.
$positions = [];
foreach ($data as $year => $yearData) {
foreach ($yearData as $position => $person) {
$positions[$position] = TRUE;
}
}
$positions = array_keys($positions);
// Define table columns.
$table = (new \Donquixote\Cellbrush\Table())
->addColName('year')
->addColNames($positions)
;
// Create thead section.
$headRow = $table->thead()->addRow('head');
$headRow->th('year', 'Year');
foreach ($positions as $position) {
$headRow->th($position, $position);
}
// Create table rows with labels based on year.
$years = array_keys($data);
$table->addRowNames($years);
foreach ($years as $year) {
$table->th($year, 'year', $year);
}
// Fill table cells in each column.
foreach ($positions as $position) {
$periodPerson = NULL;
$periodFirstYear = NULL;
$periodLastYear = NULL;
$column = $table->colHandle($position);
foreach ($years as $year) {
$person = isset($data[$year][$position])
? $data[$year][$position]
: '-';
if (!isset($periodFirstYear)) {
// First year.
$periodFirstYear = $year;
}
elseif ($person !== $periodPerson) {
// Add a table cell with rowspan.
$column->td([$periodFirstYear, $periodLastYear], $periodPerson);
$periodFirstYear = $year;
}
$periodPerson = $person;
$periodLastYear = $year;
}
if (isset($periodFirstYear)) {
// Add a table cell with rowspan.
$column->td([$periodFirstYear, $periodLastYear], $periodPerson);
}
}
print $table->render();
Any help is appreciated.
I have an array that is forfetch like this. The reason is to brake down a product in individual arrays. However I can not figure out what statement to put in the while loop so i can loop through each array in $row. initially the statement should be
while ($row = mysql_fetch_assoc($result))
however this was already done to be able to sort the array.
$sorted = array_orderby($newarray, 'volume', SORT_DESC, 'edition', SORT_ASC);
foreach($sorted as $row)
{
while( ??????? )
{
$row = build_items($row);
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}
}
Just found the answer. Sorry guys im new at PHP.
foreach($sorted AS $row) {
$row = build_items($row);
// time left till the end of this auction
$s_difference = time() - $row['starts'];
$difference = $row['ends'] - time();
$bgcolour = ($k % 2) ? 'bgcolor="#FFFEEE"' : '';
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'BID' => $row['current_bid'],
'BIDFORM' => $system->print_money($row['current_bid']),
'TIMELEFT' => FormatTimeLeft($difference),
'NUMBIDS' => $row['num_bids'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}
foreach($sorted AS $rows) {
foreach($rows AS $row) {
...
}
}
or with keys/indices
foreach($sorted AS $key => $rows) {
foreach($rows AS $index => $row) {
Yes.., we can use foreach to print all the values in an array.
Example: I have an array called "data" (SQLITE dynamic data). I want to print all the values which are there on "data" array.
By using following sample code we can print the values in a table format.
foreach ($data as $item) {
$date = $item['date'];
$url = $item['url'];
$name = $item['name'];
echo"
<tr>
<td>$date</td>
<td>$name</td>
<td>$url</td>
</tr>
";
}
Please let me know if i did any mistakes here, sorry for my bad English.
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>