PHP合并表行

时间:2012-10-05 18:58:51

标签: php html-table

我有一个DOMDocument表,看起来像这样:

 name   | user      | comment
 -----------------------------
 Test   | user1     | Line 1
 Abc    | user2     | Line 1
        |           | Line 2
 Test2  | user3     | Line 1
 Test3  | user3     | Line 1
        |           | Line 2
        |           | Line 3

正如您所看到的,有时评论会覆盖多个表格。 (显然评论很长时)
当这些换行发生时,除了注释1之外的所有字段都是空的。

如何将这些包装的注释合并在一起并输出?

我目前正在输出这样的内容:

foreach ($xml->getElementsByTagName('table')->item(1)->getElementsByTagName('tr') as $row) {
        echo "<tr>";
        foreach ($row->getElementsByTagName('td') as $column) {
            echo "<td>" . $column->textContent . "</td>";
        }
        echo "</tr>";
    }
}

1 个答案:

答案 0 :(得分:1)

在知道下一行包含的内容之前,您正在输出每一行。另一种方法是将每一行存储在一个数组中,如果下一行符合某个条件(例如换行),则允许您更正前一行。然后,您可以在处理后将结果数组输出为HTML表。

像这样(未经测试):

// build array
$rows = array();
$xmlRows = $xml->getElementsByTagName('table')->item(1)->getElementsByTagName('tr');
foreach ($xmlRows as $xmlRow) {
    $emptyFields = 0;
    $row = array();
    $xmlColumns = $xmlRow->getElementsByTagName('td');
    foreach ($xmlColumns as $xmlColumn) {
        if (empty($xmlColumn->textContent)) { // count empty fields
            $emptyFields++;
        }
        $row[] = $xmlColumn->textContent;
    }
    if ($emptyFields >= 2) { // detect if wrapping has occurred
        $lastRow = array_pop($rows); // remove last row from array
        $lastRow[2] .= $row[2]; // update last row with wrapped data
        $row = $lastRow; // use newly merged row
    }
    $rows[] = $row;
}
// output array
foreach ($rows as &$row) {
    $row = '<td>' . implode('</td><td>', $row) . '</td>';
}
echo '<table><tr>' . implode('</tr><tr>', $rows) . '</tr></table>';