PHP The essence of the table element: Table structure: The table is composed of
tags, the rows are composed of tags, and the cells are composed of tags. Column layout: |
elements are arranged next to each other within a |
row, forming columns. Row layout:
elements are arranged next to each other in a 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>
Copy after login
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;
}
Copy after login
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;
}
}
Copy after login
Conclusion
Understanding the nature of PHP table elements (rows and columns) is essential to effectively Traversing and manipulating tabular data is critical.
The above is the detailed content of Solving PHP tables: the nature of elements, columns or rows?. For more information, please follow other related articles on the PHP Chinese website!