如何将指定PHP数组转换为符合自定义格式的HTML表格?
Solution to Convert PHP Array to HTML Table
First, let's fix the core issue with your original code: it was treating each subarray as a column instead of a row, which is why all data ended up in two rows. Here's the corrected approach that meets your requirements:
Step-by-Step Explanation
- Define the Size Headers: We explicitly list the required size values (34, 35, 38, 39, 40, 41) since they're fixed per your request.
- Build the Header Row: Start with "Loc" followed by each size as table headers.
- Loop Through Each Data Entry: For every subarray in your main array, create a table row that displays the
Locvalue once, followed by the corresponding size values (ignoring the[0]element entirely).
Corrected PHP Code
<?php // Your original array $result = [ ['Loc' => 124, 0 => 124, 34 => 1, 35 => 1, 38 => 2, 39 => 2, 40 => 1, 41 => 1], ['Loc' => 424, 0 => 424, 34 => 1, 35 => 1, 38 => 0, 39 => 0, 40 => 0, 41 => 0], ['Loc' => 1512, 0 => 1512, 34 => 1, 35 => 1, 38 => 0, 39 => 0, 40 => 0, 41 => 0], ['Loc' => 1612, 0 => 1612, 34 => 0, 35 => 0, 38 => 1, 39 => 1, 40 => 2, 41 => 2], ['Loc' => 1711, 0 => 1711, 34 => 0, 35 => 0, 38 => 1, 39 => 1, 40 => 1, 41 => 1] ]; // Define the size columns we need $sizes = [34, 35, 38, 39, 40, 41]; // Start the table echo '<table border="1">'; // Header row echo '<tr>'; echo '<th>Loc</th>'; foreach ($sizes as $size) { echo "<th>$size</th>"; } echo '</tr>'; // Data rows foreach ($result as $item) { echo '<tr>'; // Display Loc once per row echo "<td>{$item['Loc']}</td>"; // Display each size value foreach ($sizes as $size) { echo "<td>{$item[$size]}</td>"; } echo '</tr>'; } // End the table echo '</table>'; ?>
Resulting HTML Table
When rendered, this code will produce a table matching your expected output:
| Loc | 34 | 35 | 38 | 39 | 40 | 41 |
|---|---|---|---|---|---|---|
| 124 | 1 | 1 | 2 | 2 | 1 | 1 |
| 424 | 1 | 1 | 0 | 0 | 0 | 0 |
| 1512 | 1 | 1 | 0 | 0 | 0 | 0 |
| 1612 | 0 | 0 | 1 | 1 | 2 | 2 |
| 1711 | 0 | 0 | 1 | 1 | 1 | 1 |
This solution ensures:
Locis shown once per row- The
[0]element is completely ignored - Only the required size columns (34-41) are displayed as headers and data
内容的提问来源于stack exchange,提问作者Bldjef
相关产品推荐
相关产品推荐

