我正在使用 PHP 自动生成一个 HTML 表格,我希望第二列右对齐。我在某处读到你可以使用 <tgroup>
和 <colspec>
去做这个。这是我的代码:
$con = mysqli_connect("localhost","user","password","dbase");
$sql="SELECT Document, COUNT(*) as count FROM table WHERE event LIKE 'Photo%' GROUP BY Document ORDER BY count DESC LIMIT 10";
$result = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
};
$colNames = array_keys(reset($data));
echo "<table id='topTen'><tgroup><colspec column='2' align='right'>";
echo "<thead><tr><th>Photo</th><th>Counts</th></tr></thead><tbody>";
foreach($data as $row) {
echo "<tr>";
foreach($colNames as $colName) {
echo "<td>".$row[$colName]."</td>";
}
echo "</tr>";
}
echo "</tbody></tgroup></table>";
mysqli_free_result($result);
mysqli_close($con);
但它不起作用。感谢您的任何建议。
最佳答案
这是一种有点粗略的方法 - 只需检查第二个 <td>
is == 2,如果是,添加样式(未测试):
$style = ''; //set var
foreach($data as $row) {
echo "<tr>";
$i=1; // start counter
foreach($colNames as $colName) {
if($i == 2){
$style = ' style="text-align: right"'; // style if second col
}
echo "<td$style>".$row[$colName]."</td>";
$style = ''; // reset style var
$i++;
}
echo "</tr>";
}
关于php - 仅格式化 PHP 生成的 HTML 表中的一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34591442/