自定义字段 - 重复器下拉列表 - 仅列出唯一值而不是空白值

Custom Fields - Repeater dropdown - list only unique & not blank values

这是我使用 ACF 中继器子字段 (firma) 来存储一些数据的事情。通常用户在这里输入他的母公司名称,如:google、alibaba、sodexo 等。所以可能会发生在多个帖子中,此字段的值将相同。目前我有以下代码:

   $args = array(
        'post_type' => 'opencourses', 
        'meta_key' => 'terminy_warsztatow'
    );

    $the_query = new WP_Query($args);

    if ($the_query->have_posts()):

        echo '<select type="text" class="form-control" name="filtr_lokalizacja">';

        while ($the_query->have_posts()) : $the_query->the_post();
                if(have_rows('terminy_warsztatow')): 
                    while (have_rows('terminy_warsztatow')) : the_row();          
                        // display your sub fields
                        $filtr_var = get_sub_field('firma'); 

                        echo '<option value="'. $filtr_var .'">'; 
                        echo $filtr_var;                                 
                        echo '</option>';

                    endwhile;

                else :
                    // no rows found
                endif;

        endwhile;

        echo '</select>'; 

    endif;  

它有效 - 意思是:它显示所有键入的值。但是它不是只显示唯一值,而是生成一个类似于此的列表:

Google 阿里巴巴

Google 索迪斯 索迪斯 特斯拉

特斯拉 索迪斯

如何避免显示相同的值并隐藏为空?我知道有 php 函数 array_unique 但我无法实现它。我做过类似的事情:

$filtr_var = get_sub_field('firma');
$result = array_unique($filtr_var);
echo $result;

但随后它根本没有显示任何值。

我假设 "firma" 是转发器中的简单文本输入类型。如果是这样,那么 arrya_unique 函数将不适用于字符串输出。

您需要将每个值保存在数组中,然后使用 in_array 函数使其唯一。

见下面的代码。 </p> <pre><code>$args = array( 'post_type' => 'opencourses', 'meta_key' => 'terminy_warsztatow' ); $the_query = new WP_Query($args); if ($the_query->have_posts()): echo '<select type="text" class="form-control" name="filtr_lokalizacja">'; while ($the_query->have_posts()) : $the_query->the_post(); if(have_rows('terminy_warsztatow')): // $PreValue = array(); while (have_rows('terminy_warsztatow')) : the_row(); // display your sub fields $filtr_var = get_sub_field('firma'); // compare current value in saved array if( !in_array( $filtr_var, $PreValue ) ) { echo '<option value="'. $filtr_var .'">'; echo $filtr_var; echo '</option>'; } // save value in array $PreValue[] = $filtr_var; endwhile; else : // no rows found endif; endwhile; echo '</select>'; endif;

希望对您有所帮助! 享受