在数组中使用php删除双值(wp-query和ACF)


Delete double values using php inside an array (wp-query and ACF)

我在我的网站上使用高级自定义字段,其中有一个选择字段(type_evenement),有5个可能的值(val_1、val_2、val_3、val_4、val_5)

我还在自定义模板页面上使用wp查询来显示类别中的帖子,所有帖子都使用"选择"自定义字段。

我试图在这个页面上显示所有的select值,但只显示一次,所以我试图使用array_unique删除双值,但它不起作用。

这是我写的代码,用来显示循环中的值,它显示所有值,即使是双值,例如val_1、val_3、val_4、val_2、val_1、val_1…

<?php 
// args
$today = date("Ymd");

$args = array (
'category' => 5,
'posts_per_page' => -1,
'meta_key'       => 'debut_date',
'orderby'       => 'meta_value_num',
'order'          => 'ASC',
'meta_query' => array(
array(
'key'       => 'fin_date',
'compare'   => '>=',
'value'     => $today,
)
),
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <?php
        $input = get_field('type_evenement');
        echo($input);
        ?>

<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>

但当使用array_unique时,将不再显示任何内容:

<?php
$input = get_field('type_evenement');
$result = array_unique($input);
echo($result);
?>

我不明白我做错了什么,我知道get_field返回一个数组,所以我想array_unique应该不工作?

如果有人能帮我,那就太好了!

非常感谢

$input只是一个值,而不是一个数组。重复项由while loop重复分配给该值。

<?php while ( $the_query->have_posts() ) : $the_query->the_post();
     $input = get_field('type_evenement');
     echo($input);

您可以修复返回重复项的查询,但由于它看起来像wordpress,这可能不起作用。

因此,您可以先填充数组,然后使用array_unique(),然后回显值(或者,如果临时数组已经包含值,则可以简单地不再添加值):

$myArr = array();
while ( $the_query->have_posts() ) {
    $the_query->the_post();
    $input = get_field('type_evenement');
    if (!in_array($input,$myArr)){
      $myArr[] = $input;
    }
 }
 foreach ($myArr AS $value){
    echo $value; //unique values.
 }