Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to a html table

Tags:

php

Can someone help me with this array that I have? I want to create a table that is a maximum of 5 columns and a maximum of 15 rows. If there are only 4 rows, for example, then only 4 rows should be shown instead of the 15. If there are only 3 cells that have data then the the remaining 2 should be padded with $nbsp;.

Here is my sample array:

Array
(
    [0] => Array
        (
            [name] => test1
            [item_id] => 1
        )
    [1] => Array
        (
            [name] => test2
            [item_id] => 2
        )
    [2] => Array
        (
            [name] => test3
            [item_id] => 3
        )
    [3] => Array
        (
            [name] => test4
            [item_id] => 4
        )
    [4] => Array
        (
            [name] => test5
            [item_id] => 5
        )
    [5] => Array
        (
            [name] => test6
            [item_id] => 6
        )
)

My data repeats if there is a new row added. This is my issue at present.

$row = count( $array ) / 5;
$col = 5;

echo'<table border="1" width="700">';

for( $i = 0; $i < $row; $i++ )
{
    echo'<tr>';
    for( $j = 0; $j < $col; $j++ ) {
        if( ! empty( $array[$j] ) ) {
            echo '<td>'.$array[$j]['item_id'].'</td>';
        }
    }
    echo'</tr>';
}

echo'</table>';
like image 552
jim Avatar asked Dec 25 '10 10:12

jim


People also ask

How do I turn an array into a table?

T = array2table( A , Name,Value ) creates a table from an array, A , with additional options specified by one or more Name,Value pair arguments. For example, you can specify row names or variable names to include in the table.

How do you convert an array to a variable?

The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value. In other words, we can say that the extract() function imports variables from an array to the symbol table.

How do I make a table in PHP using HTML?

You can create a table using the <table> element. Inside the <table> element, you can use the <tr> elements to create rows, and to create columns inside a row you can use the <td> elements. You can also define a cell as a header for a group of table cells using the <th> element.


1 Answers

Let's call your array $rows, ok?

echo "<table>";
foreach ($rows as $row) {
   echo "<tr>";
   foreach ($row as $column) {
      echo "<td>$column</td>";
   }
   echo "</tr>";
}    
echo "</table>";

Using foreach is more idiomatic for looping trough arrays in php, and it greatly increase your code's readability. Plus, the only variable you need for this is one containing the array itself.

like image 103
cbrandolino Avatar answered Oct 01 '22 23:10

cbrandolino