我有變量$count
,其中包含我的數組的所有元素。 我想將html代碼插入到另一個變量中,該變量包含與變量$ count的行數一樣多的行。 我該怎麼辦?從數組元素中創建HTML表格
<?php
$count=5;
$html="<table>
<tr>
<td></td>
<td></td>
</tr>
</table>"
?>
我有變量$count
,其中包含我的數組的所有元素。 我想將html代碼插入到另一個變量中,該變量包含與變量$ count的行數一樣多的行。 我該怎麼辦?從數組元素中創建HTML表格
<?php
$count=5;
$html="<table>
<tr>
<td></td>
<td></td>
</tr>
</table>"
?>
有很多可能性來做到這一點。
使用一個循環:
$table = '<table>';
for ($i = 0; $i < $count; $i++) {
$table .= '<tr><td></td><td></td></tr>';
}
$table .= '</table>';
或者你可以使用str_repeat
$table = '<table>';
$table .= str_repeat('<tr><td></td><td></td></tr>', $count);
$table .= '</table>';
或其他許多人 - 取決於你的需要
您可以使用此:
<?php
$count = 5;
?>
<table>
<?php for($i = 0; $i < $count; $i++) : ?>
<tr>
<td></td>
<td></td>
</tr>
<?php endfor; ?>
</table>
你能解釋downvote嗎?所以我可以通過我的錯誤糾正自己,並改善我的答案。 –
不太確定在這個問題上(它非常含糊),但我會盡力幫忙。
<?php
$count = 5;
$html = "<table>";
for($i=0;$i<$count;$i++){
$html .= "<tr><td>New Row!</td></tr>";
}
$html .= "</table>";
將此用於行。
<?php
$count = 5;
$html = "<table><tr>";
for($i=0;$i<$count;$i++){
$html .= "<td>New column!</td>";
}
$html .= "</tr></table>";
將此用於列。
結合動態行和列的100%動態表的兩個示例。如果你有一個數組,你會更好只使用一個foreach
:
<?php
$array = array(array('Col1'=>'Val1', 'Col2'=>'Val2', 'Col3'=>'Val3'), array('Col1'=>'Test', 'Col2'=>'Test', 'Col3'=>'Test'));
$html = "<table>\n\t<tr>";
//Columns
foreach(array_key($array[0]) as $col){
$html .= "\n\t\t<td>{$col}</td>";
}
$html .= "\n\t</tr>";
//Rows
foreach($array as $row){
$html .= "\n\t<tr>";
foreach($row as $rowcol){
$html .= "\n\t\t<td>{$rowcol}</td>";
}
$html .= "\n</tr>";
}
$html .= "</table>";
是我對換行和標籤有點強迫症。
如果你可以用一個用例更新你的問題,我可以提供一個更好,更準確的例子。
您可以通過兩種方式來完成。通過使用foreach或for/while循環。
在我看來,你可以繼續使用foreach來迭代你的數組()。
<?php $array= array('blue', 1, 3, 'red', 'monkey'); ?>
<table>
<?php foreach($array as $value): ?>
<tr>
<td><?php echo $value ?></td>
</tr>';
<?php endforeach; ?>
</table>
?>
對我來說,這是迭代數組的更乾淨的方式。如果您只想在一個表格上製作多個列/行,而不是使用for($i=0; $i<$count; i++)
。
線條?你的意思是行嗎?表格的內容來自哪裏? – syck
可能[str_repeat()](http://php.net/manual/de/function.str-repeat.php)是你需要的。 – syck
爲什麼這被標記爲JavaScript?我猜你對這兩種方法都開放? –