1

嗨,我认为这只是一个语法问题,但我可能正在做一些 PHP 不适合做的事情。

我正在尝试绘制一个 HTML 表格,使用一个数组来填充表格。以标题为例。

$headers 是我尝试过的标题数组:

$html_table = '
                <table border="1" cellspacing="0" cellpadding="2">
                    <tr>
                        foreach($headers as $header)
                        {
                        echo "<th> $header </th>";                          
                        }
                    </tr>
';

产生的想法是:

 <table border="1" cellspacing="0" cellpadding="2">
    <tr>
        <th>Heading 1</th>
        <th>Heading 2</th>
        <th>Heading 3</th>
        ...
        <th>Heading 99</th>
    </tr>

只需稍后要求 $html_table

可以说此刻我得到一个带有“$header”的单标题列,因为循环没有在变量方程中运行。

我将 HTML 存储为这样的变量的原因是因为我想将它与其他生成的 html 连接(使用?),即

$html_table .= '</table>';

稍后(当然,中间的实际位更复杂,与从数据库中检索数据以填充表有关。

我哪里错了?谢谢

4

3 回答 3

5

从引号中取出 foreach

$html_table = '
            <table border="1" cellspacing="0" cellpadding="2">
                <tr>';
foreach($headers as $header){
    $html_table .= "<th> $header </th>";                          
}
$html_table .='
                </tr>
';
于 2012-10-20T00:27:40.710 回答
2
$html_table = '<table border="1" cellspacing="0" cellpadding="2"><tr>'; 

foreach($headers as $header) 
  { 
    $html_table .= "<th>". $header."</th>";                           
  }
 $html_table .= '</tr>';
于 2012-10-20T00:29:22.060 回答
1
$html_table = '<table border="1" cellspacing="0" cellpadding="2"><tr>';

foreach($headers as $header)
{
    $html_table .=  '<th>'. $header .'</th>';                          
}
$html_table .= '</tr></table>';

echo $html_table;

不过,这很腐烂。您应该考虑不在 php 中回显 html ...

<table border="1" cellspacing="0" cellpadding="2">
    <tr>
        <?php foreach($headers AS $header): ?>
        <th><?php echo $header; ?></th>
        <?php endforeach; ?>
    </tr>
</table>
于 2012-10-20T00:29:49.973 回答