如何在PHP循环中去除重复值?WordPress ACF场景解决方案
解决ACF循环输出重复Location的问题
你的代码问题出在循环内部直接输出option,而且每次都把所有已收集的location拼接后塞进一个option里,导致重复生成option且内容错误。正确的做法是先收集所有location、去重,再单独循环生成每个option。
修正后的代码
<?php // 初始化空数组用于存储所有location $locations = []; // 遍历所有文章 while( have_posts() ) : the_post(); // 遍历ACF的location_info行 while ( have_rows( 'location_info' ) ) : the_row(); $location = get_sub_field( 'location' ); // 只添加非空值到数组,避免空选项 if ( !empty($location) ) { $locations[] = $location; } endwhile; endwhile; // 去重并重置数组索引 $unique_locations = array_values(array_unique($locations)); // 循环输出每个唯一的location为option foreach ( $unique_locations as $loc ) : ?> <option><?php echo esc_html($loc); ?></option> <?php endforeach; ?>
关键修正点
- 先收集再处理:把所有location收集到数组后,再统一去重,而不是在循环内部实时处理输出。
- 去重后重置索引:用
array_values()重置去重后的数组索引,避免foreach循环时出现不连续的键名问题。 - 过滤空值:添加
!empty($location)判断,防止空字段生成空的option标签。 - 安全输出:用
esc_html()转义输出内容,避免XSS安全问题。
内容的提问来源于stack exchange,提问作者jfc
相关产品推荐
相关产品推荐

