You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定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

  1. Define the Size Headers: We explicitly list the required size values (34, 35, 38, 39, 40, 41) since they're fixed per your request.
  2. Build the Header Row: Start with "Loc" followed by each size as table headers.
  3. Loop Through Each Data Entry: For every subarray in your main array, create a table row that displays the Loc value 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:

Loc343538394041
124112211
424110000
1512110000
1612001122
1711001111

This solution ensures:

  • Loc is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:28:54