PHP Array Iterator to DIV - php

I want to loop through the unknown depth array with RecursiveIteratorIterator in SELF::FIRST mode along with RecursiveArrayIterator.
If the array value is an array, I will open a DIV so the "subarray" will be inside this DIV. Something like
$array = array(
'key0' => '0',
'key1' => array(
'value0' => '1',
'value1' => '2',
),
'key2' => '3',
'key3' => array(
'value2' => '4',
'value3' => array(
'value4' => '5'
),
'value4' => array(
'value5' => '6'
),
),
);
Then the HTML should be:
<div>
<div>
<p>key0 is 0</p>
</div>
<div>
<p>key1</p>
<div>
<p>value0 is 1</p>
<p>value1 is 2</p>
</div>
</div>
<div>
<p>key2 is 3</p>
</div>
<div>
<p>key3</p>
<div>
<p>value2 is 4</p>
<p>value3</p>
<div>
<p>value4 is 5</p>
</div>
<p>value4</p>
<div>
<p>value5 is 6</p>
</div>
</div>
</div>
</div>
But the problem is my code can only close 1 <div> tag each time. I have no idea how to remember how deep was there. So I can close to a for loop and echo </div>.
My current code:
<?php
echo '<div>';
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($iterator_array), RecursiveIteratorIterator::SELF_FIRST);
$is_start = true;
$last_element = '';
foreach($iterator as $key => $value) {
if(is_array($value) && $is_start) {
echo '<div><p>' . $key . '</p>';
$is_start = false;
$last_element = end($value);
} elseif(is_array($value) && !$is_start) {
echo '</div><div><p>' . $key . '</p>';
$last_element = end($value);
} elseif(!is_array($value)) {
echo '<div><p>' . $key . ' is ' . $value . '</p></div>';
if($last_element == $value) {
echo '</div>';
}
}
}
echo '</div>';
?>

Use this recursive function
May be it will help you
get_div($array);
function get_div($arr) {
foreach($arr as $k => $a){
echo '<div>';
if(is_array($a)) {
echo "<p>".$k."</p>";
get_div($a);
} else {
echo "<p>".$k." is ".$a."</p>";
}
echo '</div>';
}
}

Related

How to auto increment in sub foreach loop?

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 />";
}
}

iterating over multi dimensional array for a menu

Hello I have a menu made in codeigniter. but I also want this to have submenu's
Therefore I get an array and go through it with a foreach loop.
<ul>
<?php foreach ($menu_item as $menu =>& $key): ?>
<li><?php echo anchor($menu, $key, $this->uri->slash_segment(1, 'leading') == $menu ? 'class="active"' : '') ?></li>
<?php endforeach ?>
</ul>
Now the problem is that this works great if its just one menu without submenu's but when I get an array like this
$menu_item = array(
'/' => 'Home',
'/about' => 'About',
'/foo' => 'boo',
'/contact' => 'contact',
'test' => array(
'foo' => 'boo'
),
'test2' => 'foo2'
);
Than it doesn't work anymore. How can I loop through everything and output it as a good menu?
You can use recursion to do that job. It takes a bit of getting your head around if you're not familiar with it, but it's very well suited to this kind of problem.
I haven't run this code in PHP, but it will give you an idea.
Basically what happens is that the main menu function checks each item to see if it's an array, and then calls the function again using the sub menu. This will work infinitely deep if required.
<?php
$menu = array(
'/' => 'Home',
'/about' => 'About',
'/foo' => 'boo',
'/contact' => 'contact',
'test' => array(
'foo' => 'boo'
),
'test2' => 'foo2'
);
?>
<ul>
<?php showMenu($menu); ?>
</ul>
<?php
function showMenu($menu)
{
<?php foreach ($menu_item as $menu =>& $key): ?>
<li><?php echo anchor($menu, $key, $this->uri->slash_segment(1, 'leading') == $menu ? 'class="active"' : '') ?></li>
if(is_array($menu_item))
{
echo "<ul>";
showMenu($menu_item);
echo "</ul>";
}
<?php endforeach ?>
}
?>
Hope this helps.
The concept of the other answers is true, but they generate invalid DOM structure, so I decided to fix it.
You can make a helper file and put the drawMenu() function inside. So, you'll be able to call the function as much as you need.
$menu = array(
'/' => 'Home',
'/about' => 'About',
'/foo' => 'boo',
'/contact' => 'contact',
'test' => array(
'foo' => 'bar',
'baz' => 'qux'
),
'test2' => 'foo2'
);
function drawMenu($menu)
{
$CI =& get_instance();
$output = '';
foreach ($menu as $key => $value) {
$output .= "<li>";
if (is_array($value)) {
$output .= anchor('#', $key);
$output .= PHP_EOL."<ul>".PHP_EOL;
$output .= drawMenu($value);
$output .= "</ul>".PHP_EOL."</li>".PHP_EOL;
} else {
$output .= anchor($key, $value, $CI->uri->slash_segment(1, 'leading') == $key ? 'class="active"' : '');
$output .= "</li>".PHP_EOL;
}
}
return $output;
}
$html = drawMenu($menu);
echo '<ul>'. $html .'</ul>';
Side-note: Usage PHP_EOL constant is arbitrary, it just makes generated DOM more readable.
Update:
I improved the drawMenu() functionality, now you can add a URL address for the headers of sub-menus:
$menu = array(
'/' => 'Home',
'/about' => 'About',
'/foo' => 'boo',
'/contact' => 'contact',
'test' => array(
'foo' => 'bar'
),
'This is Test2|/url/to/test2' => array(
'baz' => 'qux'
)
);
You can add the URL after | separator.
function drawMenu($menu)
{
$CI =& get_instance();
$output = '';
foreach ($menu as $key => $value) {
$output .= "<li>";
if (is_array($value)) {
if (strpos($key, '|') !== false) {
$param = explode('|', $key);
$output .= anchor($param[1], $param[0]);
} else {
$output .= anchor('#', $key);
}
$output .= PHP_EOL."<ul>".PHP_EOL;
$output .= drawMenu($value);
$output .= "</ul>".PHP_EOL."</li>".PHP_EOL;
} else {
$output .= anchor($key, $value, $CI->uri->slash_segment(1, 'leading') == $key ? 'class="active"' : '');
$output .= "</li>".PHP_EOL;
}
}
return $output;
}
You can check if the $key is an array: is_array
Then you can use another foreach to loop through the submenus.
try this
<ul>
<?php function buildmenu($menu_item){ ?>
<?php foreach($menu_item as $item){ ?>
<li><?php echo anchor($menu, $key, $this->uri->slash_segment(1, 'leading') == $menu ? 'class="active"' : '') ?></li>
<?php if(is_array($item)){
buildmenu($item);
} ?>
<?php } ?>
<php} ?>
<?php buildmenu($menu_item) ?>
</ul>
$menu = "<ul>\n";
foreach ($menu_item as $key => $value){
if (is_array($value)){
$menu.= "\t<li>".$key."\n\t\t<ul>\n";
foreach ($value as $key2 => $value2){
$menu .= "\t\t\t<li>".$value2."</li>\n";
}
$menu.= "\t\t</u>\n\t</li>\n";
} else {
$menu .= "\t<li>".$value."</li>\n";
}
}
$menu .= "</ul>";
echo $menu;
Output:
<ul>
<li>Home</li>
<li>About</li>
<li>boo</li>
<li>contact</li>
<li>test
<ul>
<li>boo</li>
</u>
</li>
<li>foo2</li>
</ul>

php create navigation menu from multidimensional array dynamically

I did research on this, and wasn't able to find an exact answer. Most of the questions/answers on here pertaining to this seem to be unfinished. If anyone knows of a finished solution similar to my question, please point me in that direction!
Here is my array:
Array
(
['home'] => Array
(
[0] => sub-home1
[1] => sub-home2
)
['about'] => Array
(
[0] => sub-about
['about2'] => Array
(
[0] => sub-sub-about
)
)
['staff'] => Array
(
[0] => sub-staff1
[1] => sub-staff2
)
['contact'] => contact
)
And here is what I would like to turn it into:
<ul>
<li><a href="">home<a/>
<ul>
<li>sub-home1</li>
<li>sub-home2</li>
</ul>
</li>
<li><a href="">about<a/>
<ul>
<li>sub-about</li>
<li>about2
<ul>
<li><a href="">sub-sub-about<a/></li>
</ul>
</li>
</ul>
</li>
<li><a href="">staff<a/>
<ul>
<li>sub-staff1</li>
<li>sub-staff2</li>
</ul>
</li>
<li><a href="">contact<a/></li>
</ul>
The array will be dynamically generated, but will have a limit of 3 levels ex: about->about2->sub-sub-about. I tried going off of this question: PHP/MySQL Navigation Menu but they didn't really seem to come to a conclusion? I am familiar with foreach's whiles and for loops but I just can't seem to wrap my head around this one.
EDIT: Enzino, your code works!
Here is my solution:
<?php
function MakeMenu($items, $level = 0) {
$ret = "";
$indent = str_repeat(" ", $level * 2);
$ret .= sprintf("%s<ul>\n", $indent);
$indent = str_repeat(" ", ++$level * 2);
foreach ($items as $item => $subitems) {
if (!is_numeric($item)) {
$ret .= sprintf("%s<li><a href=''>%s</a>", $indent, $item);
}
if (is_array($subitems)) {
$ret .= "\n";
$ret .= MakeMenu($subitems, $level + 1);
$ret .= $indent;
} else if (strcmp($item, $subitems)){
$ret .= sprintf("%s<li><a href=''>%s</a>", $indent, $subitems);
}
$ret .= sprintf("</li>\n", $indent);
}
$indent = str_repeat(" ", --$level * 2);
$ret .= sprintf("%s</ul>\n", $indent);
return($ret);
}
$menu = Array(
'home' => Array("sub-home1", "sub-home2"),
'about' => Array("sub-about", "about2" => Array("sub-sub-about")),
'staff' => Array("sub-staff1", "sub-staff2"),
'contact' => "contact"
);
print_r($menu);
echo MakeMenu($menu);
?>
Calvin's solution worked for me. Here's the edited version. We can use more nested loops to get sub - sub menu items.
echo '<ul>';
foreach ($menu as $parent) {
echo '<li>' . $parent . '';
if (is_array($parent)) {
echo '<ul>';
foreach ($parent as $children) {
echo '<li>' . $children . '';
}
echo '</ul>';
}
echo '</li&gt';
}
echo '</ul>';
I think you can use recursion? Here is some pseudocode, not very familiar with php.
function toNavMenu(array A){
for each element in A{
echo "<li>" + element.name + ""
if (element is an array){
echo "<ul>"
toNavMenu(element)
echo "</ul>"
}
echo "</li>"
}
}
I would probably slightly adapt the array to be something like the following:
Array(
0 => Array(
'title' => 'Home',
'children' => Array()
),
1 => Array(
'title' => 'Parent',
'children' => Array(
0 => Array(
'title' => 'Sub 1',
'children' => Array(),
),
1 => Array(
'title' => 'Sub 2',
'children' => Array(
0 => Array(
'title' => 'Sub sub 2-1',
'children' => Array(),
),
),
),
)
)
)
With a structure like this you could use recursion to build your menu HTML:
function buildMenu($menuArray)
{
foreach ($menuArray as $node)
{
echo "<li><a href='#'/>" . $node['title'] . "</a>";
if ( ! empty($node['children'])) {
echo "<ul>";
buildMenu($node['children']);
echo "</ul>";
}
echo "</li>";
}
}

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>

How do I merge same array without show it duplicate

I want to merge array which have same key to be one. Example
$options = array(
array("group" => "header","title" => "Content 1"),
array("group" => "header","title" => "Content 2"),
array("group" => "menu","title" => "Content 3"),
array("group" => "content","title" => "Content 4"),
array("group" => "content","title" => "Content 5"),
array("group" => "content","title" => "Content 6"),
array("group" => "footer","title" => "Content 7")
);
foreach ($options as $value) {
if ($value['group']) {
echo "<div class='{$value['group']}'>";
echo $value['title'];
echo "</div>";
}
}
Current output is
<div class='header'>Content 1</div><div class='header'>Content 2</div><div class='menu'>Content 3</div><div class='content'>Content 4</div><div class='content'>Content 5</div><div class='content'>Content 6</div><div class='footer'>Content 7</div>
What I want here is to be
<div class='header'>
Content 1
Content 2
</div>
<div class='menu'>
Content 3
</div>
<div class='content'>
Content 4
Content 5
Content 6
</div>
<div class='footer'>
Content 7
</div>
Let me know
$grouped = array();
foreach($options as $option) {
list($group, $title) = array_values($option);
if (!isset($grouped[$group])) {
$grouped[$group] = array();
}
$grouped[$group][] = $title;
}
foreach ($grouped as $group => $titles) {
echo sprintf('<div class="%s">%s</div>', $group, implode('', $titles));
}
$groups = array ();
foreach ( $options as $value ) {
if ( !isset ( $groups[$value['group']] ) ) {
$groups[]['group'] = $value['group']
}
$groups[$value['group']]['title'][] = $value['title'];
}
foreach ( $groups as $group ) {
echo "<div class="{$group['group']}">";
echo implode ( "\n", $group['title'] );
echo "</div>";
}
This should work, but if it doesn't matter to you, you could also just change the structure of your hardcoded-array, then you wouldn't need my first foreach.

Categories