【发布时间】:2012-07-01 14:30:26
【问题描述】:
我正在根据我的 MySQL 数据库中的某些信息制作一个 HTML 表。我需要从数据库中获取的表包含行(rowid、rowname)、列(columnid、columnname) 和单元格数据。一个表格,将行和列中的 ID 链接在一起(cellid、rowid、columnid、somedata)。 该表如下所示:
__________| column1 | column2 | column3 | ...
row1 | somedata | somedata | |
----------|----------|----------|----------|-----
row2 | somedata | | somedata |
----------|----------|----------|----------|-----
... | | | |
我的方法是使用几个嵌套的 foreach 循环,如下所示:
$rows = new Rows(); //These objects are containers for objects
$columns = new Columns(); //that hold some of the database data.
$alldata = new Alldata(); //MySQL queries within these objects are irrelevant, I think. They already get the relevant data
$count = count($alldata);
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
foreach ($alldata->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) { //If the column has data the related to the row
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) { //if loop couldn't find any entries, it prints an empty cell
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
暴力破解,当数据库中的任何一张表都有几百行数据时,显然这不是很有效的方法,我不喜欢这样。 任何想法如何提高效率?有没有更好的方法来创建我需要的表格?
编辑:
这个问题思考了一周,终于给了我一些答案。就是这么简单!
我对我的 Column 对象类做了一些修改。以前,我的代码遍历了数据库中 celldata 表上所有可能的条目。现在 Column 对象得到一个 celldata 数组,其中 columnid's 匹配,我可以只使用该数据进行比较。
$rows = new Rows();
$columns = new Columns();
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
$count = count($column->getAlldata());
foreach ($column->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) {
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) {
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
速度更快,虽然仍然是暴力破解,但需要处理的数据量更少。当然,现在的问题是 Column 对象可能会执行相当多的 MySQL 查询,具体取决于有多少 Columns。
【问题讨论】:
-
行和列ID是否保证按数字顺序排列?
-
@eggyal 行和列按名称排序,所以没有。
标签: php mysql object foreach html-table