我的网站上有很多表,每个表都包含两列:标题和SQL数据库中的值。我目前正在使用以下内容将数据放入表中:
<table>
<tr>
<td class = "item">House</td>
<td class = "req"><?php $row_buyerdetails['tod_house']; ?></td>
</tr>
<tr>
<td class = "item">Bungalow</td>
<td class = "req"><?php $row_buyerdetails['tod_bung']; ?></td>
</tr>
</table>
这似乎是一种创建表格的冗长方式(特别是因为我将拥有比此更多的行以及相当多的单独表格)。另外,如果我想更改类名,例如,Id必须更改每个表中的每一行!必须有一种方法将'item'和'req'对放在一个数组中,然后创建一个循环来制作表,填充数据库中的数据并分配类?我是PHP的新手,所以无法解决如何做到这一点!
上面的表格代码将创建下表:
表格布局是我想要的。但是,我不想输入每行代码,我想在数组中放置住宅类型(带有'item'类)和数据库中的结果(带有'req'类),然后循环遍历此数组以创建表,而不是为每行和每个表键入每个<tr>
和<td>
。我只是不知道PHP中的技术循环并创建不同的标签,将数据插入到它们中,并分别为每个<td>
分配一个类!
答案 0 :(得分:3)
虽然你的问题不太清楚,但我建议从我的理解中找到解决方案。
您可以使用foreach循环。首先,将要显示在页面上的标题(“House”,“Bungalow”,..)存储在与数据库表中的标题关联的数组中。
所以它会像
<?php $arrTitles = array("tod_house"=>"House", "tod_bung"=>"Bungalow"); ?>
你的表格代码应该是
<table>
<?php
foreach($row_buyerdetails as $k=>$v) {
?>
<tr>
<td class = "item"><?php echo $arrTitles[$k]; ?></td>
<td class = "req"><?php echo $v; ?></td>
</tr>
<?php
}
?>
</table>
答案 1 :(得分:1)
您可以创建一个视图助手函数,它将接受一个数组并返回一个表。记下htmlspecialchars
的用法。
function create_table(array $rows, $headingClassName = '') {
$buffer = '<table>';
foreach ($rows as $row) {
$buffer .= '<tr><td';
if ($headingClassName) {
$buffer .= ' class="' . htmlspecialchars($headingClassName) . '"';
}
$buffer .= '>' . htmlspecialchars($row['name']) . '</td><td';
if ($row['class']) {
$buffer .= ' class="' . htmlspecialchars($row['class']) . '"';
}
$buffer .= '>' . htmlspecialchars($row['value']) . '</td></tr>';
}
$buffer .= '</table>';
return $buffer;
}
从数据库接收信息后代码的外观示例:
// row received from database (column => value)
$row_buyerdetails = array(
'tod_house' => 1,
'tod_bung' => 1,
'tod_flat' => 1,
'tod_conv' => 1,
'tod_farm' => 0,
'tod_hold' => 0,
'tod_plot' => 1
);
// describe the headings for the rows from the database
$headings = array(
'tod_house' => 'House',
'tod_bung' => 'Bungalow',
'tod_flat' => 'Flat',
'tod_conv' => 'Barn Conversion',
'tod_farm' => 'Farm',
'tod_hold' => 'Small Holding',
'tod_plot' => 'Building Plot'
);
// convert integers to yes/no and add the req class. you can do this more elegantly
// by modifying the create_table method which would remove the need for this loop.
array_walk($row_buyerdetails, function (&$value, $key) use ($headings) {
$value = array(
'class' => 'req',
'name' => $headings[$key],
'value' => $value ? 'yes' : 'no'
);
});
最后,您可以在视图中输出表格:
<?php echo create_table($row_buyerdetails, 'item'); ?>
答案 2 :(得分:-1)
<table>
foreach ($results as $row) {
echo '<tr>';
echo '<td class = "item">House</td>';
echo '<td class = "req">'. $row_buyerdetails['tod_house'] .'</td>';
echo '</tr>';
echo '<tr>';
echo '<td class = "item">Bungalow</td>';
echo '<td class = "req">'. $row_buyerdetails['tod_bung'].'</td>';
echo '</tr>';
}
</table>