How to print 2d php array with header - php

How can I generate header for printed 2d array in php?
So my array look like this:
$tab=array(
array(0,1,2,3),
array(1,2,3,4),
array(2,3,4,5)
)
This code:
foreach ($tab as $key => $row){
echo '<b>o<sub>'.($key+1).'</sub></b> ';
foreach ($row as $item) {
echo $item.' ';
}
echo '<br>';
}
Print this:
o1 0 1 2 3
o2 1 2 3 4
o3 2 3 4 5
But I need this:
a1 a2 a3 d
o1 0 1 2 3
o2 1 2 3 4
o3 2 3 4 5
Where lenght of rows may be diferent and last column always must be d
Thanks for help

You can check if this is the first iteration in the first foreach and if so, add the first line.
foreach ($tab as $key => $row) {
// If first iteration, add the header
if ($key === 0)
{
foreach ($row as $i => $item)
{
// Last header must be 'd'
if ($i === count($row) - 1)
echo '<b>d</b>';
else
echo '<b>a<sub>' . ($i + 1) . '</sub></b> ';
}
echo '<br />';
}
// Add the current row
echo '<b>o<sub>' . ($key + 1) . '</sub></b> ';
foreach ($row as $item) {
echo $item . ' ';
}
echo '<br />';
}

If the first row is a static row, then you can simply print it using echo function at first.
But if its a dynamic tab as well, then you can use the following code:
$count = count($tab[0]);
for($i = 1; $i <= $count; $i++)
{
if($i != $count) echo '<b>a<sub>' . ($i + 1) . '</sub></b> ';
else echo '<b>d</b> ';
}
foreach ($tab as $key => $row){
echo '<b>o<sub>'.($key+1).'</sub></b> ';
foreach ($row as $item) {
echo $item.' ';
}
echo '<br>';
}

You can try this, except use <table> or <div> to align your elements.
foreach ($tab[0] as $key => $item)
echo $key === 0 ? title(' ', ' ') : title('a', $key);
echo title('d', '') . '<br>';
function title(string $letter, string $index)
{
return "<b>{$letter}<sub>{$index}</sub></b>";
}

Related

Transpose rows and columns in a 2D array [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 4 years ago.
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:
//Creating rows and columns for text file
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($result as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";
}
function transpose_matrix($result) {
$transpose = array(); //
foreach ($result as $key => $sub) {
foreach ($sub as $subkey => $subvalue) {
$transpose[$subkey][$key] = $subvalue;
}
}
return $transpose;
}
My first table displays as expected and looks somthing like this:
1 2 3 4 5
6 7 8 9 10
I need it to appear as such (i.e rotating the position of the rows and columns):
1 6
2 7
3 8
4 9
5 10
I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix
This should give you what you need.
function transpose($array_one) {
$array_two = [];
foreach ($array_one as $key => $item) {
foreach ($item as $subkey => $subitem) {
$array_two[$subkey][$key] = $subitem;
}
}
return $array_two;
}
Then just pipe your existing array into the function and render the resulting array.
Check this: https://3v4l.org/OnuSu
$table = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
];
$i = 0;
$transpose = [];
while ($columns = array_column($table, $i++))
{
$transpose[] = $columns;
}
$table = '<table border="1">';
$rows = count($transpose);
for ($i = 0; $i < $rows; $i++){
$cols = count($transpose[$i]);
$table .= '<tr>';
for ($j = 0; $j < $cols; $j++)
{
$table .= '<td>' . $transpose[$i][$j] . '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
echo $table;
You can just extract the columns of the sub-arrays one-by-one:
foreach(reset($result) as $key => $values) {
$transpose[] = array_column($result, $key);
}
However this is probably better and should work even if the keys are different in each array:
$transpose = array_map(null, ...$result);
Your function seems to be working fine you just need to call it.
Add this below the function:
//Creating rows and columns for text file
$result[0] = ['1','2','3','4','5'];
$result[1] = ['6','7','8','9','10'];
$result[2] = ['11','12','13','14','15'];
$result[3] = ['16','17','18','19','20'];
$result[4] = ['21','22','23','24','25'];
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($result as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";
function transpose_matrix($result) {
$transpose = array(); //
foreach ($result as $key => $sub) {
foreach ($sub as $subkey => $subvalue) {
$transpose[$subkey][$key] = $subvalue;
}
}
return $transpose;
}
$mat = transpose_matrix($result);
echo "<h1>Data Table</h1>";
echo "<table border = 0 >";
foreach($mat as $key=>$value){
echo "<tr>";
foreach($value as $v){
echo "<td>".$v."</td>";
}
echo "</tr>";
}
echo "</table>";

Error create multi columns in php not use table

I have a sample list 1,2,3,4,5,6,7,8
I want create 3 colums with format
1 4 7
2 5 8
3 6
This is my code
$columns = 3;
$rows = ceil(count($lists) / $columns);
foreach ($lists as $key => $value) {
if($key % $rows == 0) {
echo '<div class="col-md-4">';
}
echo $value;
if($key % $rows == 0) {
echo '</div>';
}
}
This is result error
<div class="col-md-4">1</div>
2
3
<div class="col-md-4">4</div>
5
6
<div class="col-md-4">7</div>
8
How to fix it for result:
<div class="col-md-4">1 2 3</div>
<div class="col-md-4">4 5 6</div>
<div class="col-md-4">7 8</div>
This solution works for your last edit:
<div class="col-md-4">1 2 3</div>
<div class="col-md-4">4 5 6</div>
<div class="col-md-4">7 8</div>
So, code is:
$lists = array(1,2,3,4,5,6,7,8);
$columns = 3;
$rows = ceil(count($lists) / $columns);
echo '<div class="col-md-4">';
foreach($lists as $key => $value) {
if ($key % $rows == 0 && $key != 0) {
echo '</div><div class="col-md-4">'.$value.' ';
} else {
echo $value.' ';
}
}
echo '</div>';
... because you're only adding the div to every third value. I think this is what you want
$columns = 3;
$rows = ceil(count($lists) / $columns);
foreach ($lists as $key => $value) {
if($key % $rows == 0) {
echo '<div class="row">';
}
echo '<div class="col-md-4">' . $value . '</div>';
if($key % $rows == 0) {
echo '</div>';
}
}
It's a lot simpler to achieve what you're after. Say you have the following list:
$list = '1,2,3,4,5,6,7,8';
All you'd have to do is explode your string (list) into an array and chunk that into groups of 3. Now that simplifies what you are required to do when printing out your rows:
$chunks = array_chunk(explode(',', $list), 3);
foreach($chunks as $row){
echo "<div class='row'>";
foreach($row as $value){
echo "<div class='col-md-4'>{$value}</div>";
}
echo "</div>";
}
Example/Demo
References
array_chunk()
explode()
Assuming you need fixed 3 columns, here the code (you may have to fix the code based on your column requirement)
$columns = 3;
$lists = array(1,2,3,4,5,6,7,8);
$rows = ceil(count($lists) / $columns);
$i = 0;
while($i < $rows)
{
echo "<div class=col-xs-4>".#$lists[$i]."</div>";
echo "<div class=col-xs-4>".#$lists[$i+$rows]."</div>";
echo "<div class=col-xs-4>".#$lists[$i+$rows+$rows]."</div>";
$i++;
}

How to show the value of two related arrays in php?

I have two arrays myarray1 has name of images and myarray2 has the address of images,
I am going to show image names and their addresses in pagination but do not know how to complete the code.
$pages = array_chunk($myarray1,10);
$addrs = array_chunk($myarray2,10);
$page_number = 1
$count = 0;
echo'<table>';
echo'<tr>';
foreach ($pages[$page_number] as $i) {
$counter++;
if ($count == 5) {
echo '</tr><tr>';
$counter = 0;
}
echo'<td>'.$i. " AND " . <<Value of addrs array goes here
echo'</td>';
}
.......
I'll do it on this way
$count = 1;
foreach ($pages[$page_number] as $key => $i) {
if ($count % 5 == 0) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
$count++; // increase at the end.
}
if you can try to var_dump those arrays before foreach just to be clear how structure looks like.
Try something like this: (note also the counter++ is changed in $count++)
foreach ($pages[$page_number] as $key => $i) {
$count++;
if ($count == 5) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
$count = 0;
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
}

To get the multi dimention array values in php

I have a multi-dimension array in php like this
$shop = array(
array("name","point","number"),
array('Ranjit', 1.25 , 15),
array('Pitabas', 0.75 , 25),
array('Khela', 1.15 , 7)
);
Now I have to show the output like this
name-> ranjit
Point-> 1.25
number->15
name->Pitabas
Point->0.75
number->25
name->Khela
Point->1.15
number->7
I am trying for loop, but I could get the result in nested forloop. Please help me to get the answer.
My solution:
$headings = array_shift($shop);
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $headings[$key], '=>', $value;
}
}
Here's a simple loop: Observe that we skip the first element of the outer array, which is deemed to contain the headers:
for ($i = 1; $i != count($shop); ++$i)
{
print $shop[0][0] . ": ". $shop[$i][0] . "\n";
print $shop[0][1] . ": ". $shop[$i][1] . "\n";
print $shop[0][2] . ": ". $shop[$i][2] . "\n";
}
You know the first row will be the titles, so store them separately:
$titles = $shop[0];
That will give you
$titles = array('name', 'point', 'number');
Then loop through your array:
foreach ($shop as $index => $row) {
if ($index == 0)
continue;
foreach($row as $column => $item) {
echo $titles[$column] . " -> " . $item . "<br />";
}
}
This should give the desired output:
for($x = 1, $lim = sizeof($shop); $x < $lim; $x++)
{
echo $shop[0][0]."->".$shop[$x][0]."<br>";
echo $shop[0][1]."->".$shop[$x][1]."<br>";
echo $shop[0][2]."->".$shop[$x][2]."<br>";
}

display php foreach values in div

I have
foreach ($a as $key => $value) {
echo "<DIV id='container'>
<DIV id='middle'>$value</DIV>
</DIV>";
//echo "<br />$key:$value<br />\n";
}
which displays result one below other,
like
1234
5678
2010-05-20
5678
1590
2010-05-19
but i want it in a table like structure like
1234 5678 2010-05-20
5678 1590 2010-05-19
how can i do that?
You could keep track with for example modulus if you should begin a new row or not.
EDITED after reformatting of the question
I think what you need is simply something on the line of:
echo '<table><tr>';
$n = 0;
foreach ($a as $key => $value)
{
if ($n==3)
{
$n = 0;
echo '</tr><tr>';
}
echo '<td>'.$value.'</td>';
$n++;
}
echo '</tr></table>';
You can do like:
$counter = 0;
foreach ($a as $key => $value) {
$counter++;
if (($counter % 3) === 0)
{
echo "<DIV id='container'>
<DIV id='middle'>$value</DIV>
</DIV>";
}
else
{
echo "<DIV id='container' style='float:left;'>
<DIV id='middle'>$value</DIV>
</DIV>";
}
}
Kind of what nico was saying:
foreach ($a as $key => $value)
{
echo '<div style="width:33%;float:left">'.$value.'</div>';
}
Or what don was saying:
$i = 0;
$open = false;
echo '<table>';
foreach( $a as $key => $value )
{
if( 0 == $i % 3 ) {
echo '<tr>';
$open = true;
}
echo "<td>$value</td>";
if( 2 == $i % 3 ) {
echo '</tr>';
$open = false;
}
$i++;
}
if( $open )
echo '</tr>';
echo '</table>';
Simply use like this,
foreach ($a as $key => $value) {
echo "<DIV id='container' style='display:inline'>
<DIV id='middle' style='display:inline'>$value</DIV>
</DIV>";
//echo "<br />$key:$value<br />\n";
}
add the break statement depending on your second line.
By default, div's don't float next to each other. You could give all the div's, except every third one float: left in the style. However it's okay to use table's if your displaying a table.
If you can derive from the value of $key wether to start a new row or not you can do something like:
echo '<table><tr>';
foreach ($a as $key => $value) {
if($key == 'somevalue'){
//start a new row if the $key allow
echo '</tr><tr>';
}
echo '<td>'.$value.'</td>';
}
echo '</tr></table>';
If you can't derive from the value of $key wether to start a new row or not, use a counter, like so:
echo '<table><tr>';
$cnt = 0;
foreach ($a as $key => $value) {
if($cnt % 3 == 0){
//start a new row if this row contians 3 cells
echo '</tr><tr>';
}
echo '<td>'.$value.'</td>';
$cnt++;
}
echo '</tr></table>';

Categories