本文讲解如何在 php(特别是 wordpress acf 环境下)遍历数据时,智能识别**连续重复值**并为表格 `
在动态生成产品规格表(如电压、颜色、尺寸等横向对比)时,常见需求是:当某字段(如 voltage)出现连续相同值(如 12, 12, 24, 24),对应
✅ 正确解法是采用 “滑动窗口式分组计数”:仅当值发生变化时才输出上一段的合并单元格,并重置计数器。无需关联数组或复杂键名——只需两个状态变量:
以下是重构后的核心逻辑(适配 WordPress ACF have_rows() 循环):
if (have_rows('product_variations')) {
// 初始化状态变量(注意:初始值设为 null 或空字符串,确保首次必触发输出)
$currentVoltage = null;
$spanCount = 0;
$pvoltage = ''; // 存储最终电压行 td 字符串
// 第一次遍历:收集所有电压值到数组(便于后续分组处理,更清晰可控)
$voltages = [];
while (have_rows('product_variations')) : the_row();
$voltages[] = get_sub_field('voltage');
endwhile;
// 第二次遍历:按连续相同值分组,生成 colspan
for ($i = 0; $i < count($voltages); $i++) {
$v = $voltages[$i];
if ($v === $currentVoltage) {
// 值相同:仅增加计数
$spanCount++;
} else {
// 值变化:先输出上一组(若存在),再重置
if ($currentVoltage !== null) {
$pvoltage .= '' . esc_html($currentVoltage) . ' ';
}
$currentVoltage = $v;
$spanCount = 1; // 新组从 1 开始
}
}
// 循环结束后,输出最后一组
if ($currentVoltage !== null) {
$pvoltage .= '' . esc_html($currentVoltage) . ' ';
}
// 构建完整表格(其他字段同理可复用此模式)
$output = '| '; // 动态生成表头(name 字段) rewind_rows('product_variations'); // 重置 ACF 行指针 while (have_rows('product_variations')) : the_row(); $output .= ' | ' . esc_html(get_sub_field('name')) . ' | '; endwhile; $output .= '
|---|---|
| Voltage | ' . $pvoltage . '
? 关键要点说明:
function buildColspanCells($values, $align = 'center') {
if (empty($values)) return '';
$html = ''; $current = null; $count = 0;
foreach ($values as $v) {
if ($v === $current) {
$count++;
} else {
if ($current !== null) {
$html .= '' . esc_html($current) . ' ';
}
$current = $v;
$count = 1;
}
}
if ($current !== null) {
$html .= '' . esc_html($current) . ' ';
}
return $html;
}
// 使用:$pvoltage = buildColspanCells($voltages);⚠️ 常见陷阱规避:
通过这种清晰的两阶段处理(采集 → 分组),代码可读性、可维护性与健壮性大幅提升,轻松应对 12,12,24,24 或 12,24,12,24 等任意排列组合。