我有一个变量$count
,它包含我的数组的全部元素。我想将html代码插入到另一个变量中,该变量包含的行数与变量$count的行数一样多的表。我该怎么办?
<?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_repeak
$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>
对这个问题不太确定(非常模糊),但我会尽力提供帮助。
<?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来迭代您的array()。
<?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++)
。