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

956 views Asked by At

I'm using advanced custom fields on my website with a select field (type_evenement) with 5 possible values (val_1, val_2, val_3, val_4, val_5)

I'm using also a wp query on a custom template page to display posts from a category, all posts uses the "select" custom field.

I'm trying to display all the select values on this page, but only once, so I'm trying to delete the double values, using array_unique, but it's not working.

here is the code I wrote to display the values inside the loop, it display all the values, even when double, for example, 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(); ?>

but when using array_unique, nothing is displayed anymore :

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

I don't understand what I'm doing wrong, I know that get_field returns an array, so I guess that array_unique should work no ?

If someone can help me with this would be nice !

thanks a lot

1

There are 1 answers

1
dognose On BEST ANSWER

$input is just a single value, not an array. The duplicates are repeatedly assigned to that value by the while loop.

<?php while ( $the_query->have_posts() ) : $the_query->the_post();

     $input = get_field('type_evenement');
     echo($input);

You could either fix the query that returns the duplicate, but since it looks like wordpress, that might not going to work.

So you could fill an array first, then use array_unique() and then echo the values (or you could simple not add a value again, if the temporary array already contains it):

$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.
 }