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

如何用PHP为数组动态生成的表格重复数据添加rowspan

Alright, let's tackle this dynamic table rowspan problem in PHP. I've built similar tables for repeating data before, so here's a practical, easy-to-follow approach that covers both general duplicate data handling and your specific requirement for "Youth Classes".

PHP Dynamic Table with RowSpan for Duplicate Data

The goal is to generate an HTML table from an array, automatically add rowspan for repeated categories, and ensure "Youth Classes" only shows once with a fixed rowspan=2.

1. Start with Sample Data

First, let's define a sample array that mirrors your use case—including duplicate entries for "Youth Classes":

$classData = [
    ['category' => 'Adult Classes', 'class_name' => 'Yoga Basics'],
    ['category' => 'Youth Classes', 'class_name' => 'Kids Karate'],
    ['category' => 'Youth Classes', 'class_name' => 'Junior Dance'],
    ['category' => 'Adult Classes', 'class_name' => 'Advanced Pilates'],
    ['category' => 'Senior Classes', 'class_name' => 'Low-Impact Fitness']
];

2. Core Logic: Handle RowSpan & Special Category

We'll track the current category and use a flag to handle the "Youth Classes" special case. Here's the full code:

// Initialize tracking variables
$currentCategory = '';
$youthRendered = false;

// Start building the table
echo '<table border="1" cellpadding="8" cellspacing="0">';
echo '<thead><tr><th>Class Category</th><th>Class Name</th></tr></thead>';
echo '<tbody>';

foreach ($classData as $index => $class) {
    $category = $class['category'];
    $className = $class['class_name'];

    // Handle the special "Youth Classes" case first
    if ($category === 'Youth Classes') {
        if (!$youthRendered) {
            // First occurrence: render the category with rowspan=2
            echo '<tr>';
            echo '<td rowspan="2">' . htmlspecialchars($category) . '</td>';
            echo '<td>' . htmlspecialchars($className) . '</td>';
            echo '</tr>';
            $youthRendered = true;
        } else {
            // Subsequent occurrence: only render the class name
            echo '<tr>';
            echo '<td>' . htmlspecialchars($className) . '</td>';
            echo '</tr>';
        }
        continue; // Skip general logic for this category
    }

    // General logic for other categories
    if ($category !== $currentCategory) {
        // New category: calculate how many rows it needs to span
        $rowCount = count(array_filter($classData, function($item) use ($category) {
            return $item['category'] === $category;
        }));
        $currentCategory = $category;

        // Render category with rowspan and first class name
        echo '<tr>';
        echo '<td rowspan="' . $rowCount . '">' . htmlspecialchars($category) . '</td>';
        echo '<td>' . htmlspecialchars($className) . '</td>';
        echo '</tr>';
    } else {
        // Same category: only render the class name
        echo '<tr>';
        echo '<td>' . htmlspecialchars($className) . '</td>';
        echo '</tr>';
    }
}

echo '</tbody></table>';

3. Key Details Explained

  • Special Case Handling: The $youthRendered flag ensures "Youth Classes" is only printed once, with a fixed rowspan=2—even if you add more entries later, you can adjust the rowspan value easily.
  • General Duplicate Handling: For other categories, we dynamically count how many entries belong to the current category using array_filter, so the rowspan automatically adjusts if your data changes.
  • Security: We use htmlspecialchars() to sanitize output, preventing potential XSS attacks if your data comes from user input.

4. Final Output

The generated table will look like this (formatted for readability):

Class CategoryClass Name
Adult ClassesYoga Basics
Advanced Pilates
Youth ClassesKids Karate
Junior Dance
Senior ClassesLow-Impact Fitness

内容的提问来源于stack exchange,提问作者BrianC987

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:09:50