如何从ACF嵌套Repeater的两个字段数组中获取最大值?
解决方案:获取ACF嵌套Repeater字段中的最大值
原代码的核心问题
array_push使用错误:array_push的返回值是数组的新长度,不是数组本身,你把$groupB赋值成了数字,导致后续操作完全失效。- 文本类型未转数字:所有子字段是文本类型,直接存入数组会以字符串形式存储,用
max()比较时会按字符串规则(比如"9"会被判定为大于"10"),结果错误。 - 输出时机错误:在主Repeater的循环内每次执行
echo,导致多轮循环输出多个结果,应该等所有数据收集完成后再计算最大值。
修复后的完整代码
<?php // 初始化存储所有折扣值的数组 $all_percentages = []; if (have_rows('sales')) : while (have_rows('sales')) : the_row(); // 处理全局区域折扣:转成数字后加入数组 $global_discount = get_sub_field('all_regions_percentage_off'); if (is_numeric($global_discount)) { $all_percentages[] = (float)$global_discount; } // 处理嵌套区域的折扣 if (have_rows('different_regions')) : while (have_rows('different_regions')) : the_row(); $region_discount = get_sub_field('percentage_off'); if (is_numeric($region_discount)) { $all_percentages[] = (float)$region_discount; } endwhile; endif; endwhile; // 计算并输出最大值 if (!empty($all_percentages)) { $max_discount = max($all_percentages); echo "最大折扣:{$max_discount}%"; } else { echo '没有有效折扣数据'; } else : echo 'Nothing here, sorry'; endif; ?>
关键修复说明
- 统一数组存储:只用一个数组
$all_percentages收集所有折扣值,避免多余变量造成混淆。 - 数值类型转换:每次获取字段值后,先通过
is_numeric验证有效性,再转成float类型,确保数值比较逻辑正确。 - 延迟输出逻辑:将最大值计算和输出放在主循环外部,只执行一次,避免多轮循环重复输出。
- 容错处理:增加空数组判断,避免没有有效数据时调用
max()报错。
内容的提问来源于stack exchange,提问作者Julia Galden
相关产品推荐
相关产品推荐

