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>';
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With