[英]how to create table with dynamic column using php
假設array中有多個項目。這可能是奇數甚至像我有一個包含從a到z的項目的數組現在我要在表中顯示該項目。 但是,正如您所知道的那樣,我想在表中顯示這些字母(該表最后僅包含5列),所以我只想在表中顯示它們。我想在表中顯示這些字母。 最后我希望應該有三列而不是5。
這是我的代碼,我不知道該怎么辦?
但是我在下面的代碼中遇到的問題是第二個循環不正確。
<?php
$arr=array('a','b','c','d','e','f','g','h');
$count= sizeof($arr);
$row=ceil($count/5);
echo "<table border='1'>";
for($r=0;$r<$row;$r++){
echo "<tr>";
for($j=0;$j<=5;$j++){
echo "<td>'".$arr[$j]."'</td>";
}
echo "</tr>";
}
echo "</table>";
?>
我的方法使用array_slice
提取源片段並構建行:
$arr=array('a','b','c','d','e','f','g','h');
$offset = 0;
$num_columns = 5; //adjust number of columns
$table_html = "<table border='1'>";
while($slice = array_slice($arr,$offset,$num_columns)){
$offset += $num_columns;
$row_html = '';
foreach($slice as $n) $row_html .= "<td>$n</td>";
$table_html .= "<tr>$row_html</tr>";
}
$table_html .= '</table>';
echo $table_html;
嘗試下面的代碼。 聲明變量中所需的列數,因此可以隨時更改。 當循環計數與要顯示的列數相同時,關閉tr
標簽。
<?php
$arr=array('a','b','c','d','e','f','g','h');
$columnLength = 5;
echo "<table border='1'>";
echo "<tr>";
for($r=0;$r<count($arr) ; $r++){
echo "<td>'".$arr[$r]."'</td>";
if($r + 1 == $columnLength ) {
echo "</tr>";
}
}
echo "</table>";
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.