仅格式化PHP生成的HTML表中的一列

时间:2016-01-04 12:42:00

标签: php html css

我正在使用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); 

但它不起作用。感谢任何建议。

2 个答案:

答案 0 :(得分:0)

这有点粗糙 - 只需检查第二个<td>是否= = 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>";
}

答案 1 :(得分:0)

尝试:

#topTen tr td:first-child + td { text-align:right; }

这仅针对第二列(而不是使用td:nth-​​child(2),它将定位每一列,但这假设您有两列以上)。