【发布时间】:2016-01-19 13:21:25
【问题描述】:
我对 PHP 很陌生,所以请原谅我提出这个简单的问题,但我无法正确格式化一个简单的表格。
我使用 PHP 从 MYSQL 获取结果并将其显示在 HTML 页面中。表格左侧和顶部有 ID 标签,正文是数字。
这是 PHP 代码:
$sql = "CALL pivot('DATA', 'amount', 'scen_id', 'dim2_id', 'where ent_id=''abc1''')";
$res = mysqli_query($mysqli, $sql) or die('Query failed: ' . mysqli_error($mysqli));
$row = mysqli_fetch_assoc($res);
echo '<table>';
// printing table header
foreach($row as $name => $value) {
echo "<th>$name</th>";
}
// printing table rows
while($row = mysqli_fetch_row($res))
{
echo "<tr>";
foreach($row as $cell)
echo "<td>$cell</td>\n";
echo "</tr>\n";
}
echo '</table>';
这是我得到的:
scen_id ProdA ProdB ProdC Total
BUD 59903423 66278016 55422083 181603522
FORC 37195845 52753807 41339980 131289632
Total 157331578 185154736 164437401 506923715
虽然这比空白页要好,但缺少数据的第一行(包含 ACT... 等)。当我在 Mysql 中运行查询时,它确实出现了。我希望一切都正确对齐,并且数字用千位分隔符格式化。我知道您不能为此使用 CSS。
我已经尝试过任何东西,比如这个:
echo "<td>".number_format($cell)."</td>\n";
但是结果是这样的:
scen_id ProdA ProdB ProdC Total
59,903,423 66,278,016 55,422,083 181,603,522
37,195,845 52,753,807 41,339,980 131,289,632
157,331,578 185,154,736 164,437,401 506,923,715
没有更多的行标签......而且仍然没有正确对齐。仍然缺少第一行。我希望有人能告诉我如何让它工作。我想这是一项标准任务,没有人会问这个问题。我在网上找不到太多内容。
编辑:好的问题解决了,谢谢大家!为了完整起见:这是我的工作代码;
$sql="CALL pivot('DATA', 'amount', 'scen_id', 'dim2_id', 'where ent_id=''abc1''')";
$res=mysqli_query($mysqli, $sql) or die('Query failed: ' . mysqli_error($mysqli));
echo '<table>';
$first = true;
while($row = mysqli_fetch_assoc($res)) {
if ($first) {
foreach(array_keys($row) as $name) {
echo "<th>$name</th>";
}
$first = false;
}
echo "<tr>";
foreach($row as $cell)
if (!is_numeric($cell))
{echo "<td>$cell</td>\n";}
else
{echo "<td>".number_format($cell)."</td>\n";}
echo "</tr>\n";
}
echo '</table>';
?>
这里是 CSS 代码:
table tr td, table tr th {
text-align: right;
font-size: 10px;
font-family: Verdana, 'Lucida Grande', Helvetica, Arial, Sans-Serif;
padding: 0 4px;
}
【问题讨论】:
-
你取出一行然后把它扔掉,然后进入你的 while() 循环。一旦你
fetch()ed 一行,它就消失了。