to form rows.
Solving PHP tables: the nature of elements, columns or rows?
Tables in PHP organize data using the <table>, <code><tr>, and <code><td> tags. <code><table> is the table itself, <code><tr> is the row, <code><td> is the cell. <p>Understanding the nature of elements is critical to traversing and manipulating tabular data. </p>
<p><strong>Columns vs Rows</strong></p>
<ul><li>
<strong>Columns: </strong><code><td> Elements in a <code>
Arrange adjacently within the row.
Row: <tr> An element is a group of <code><td> arranged adjacently in <table>
<code>
Cell. Practical case: Get table data
Consider the following table:
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
</tr>
</table>
To get the names of all rows in the table:
$table = document->getElementsByTagName('table')[0];
$rows = $table->getElementsByTagName('tr');
$names = [];
foreach ($rows as $row) {
$cells = $row->getElementsByTagName('td');
$name = $cells[0]->textContent;
$names[] = $name;
}
To get all cells in column 1 of the table:
$cells = $table->getElementsByTagName('td');
$column1 = [];
foreach ($cells as $cell) {
if ($cell->parentNode === $rows[0]) {
$column1[] = $cell->textContent;
}
}
Conclusion
Understanding the nature of PHP table elements (rows and columns) is essential to effectively Traversing and manipulating tabular data is critical.