I am looking for a way to strip out duplicate content from an array. The problem is that these are essentially all different arrays obtained from while loop
I have 2 custom post types "Schools" and "Courses" that have an ACF field of relationships between each other. On the course taxonomy pages, I display the courses of the current taxonomy, as well as schools related to the courses of this taxonomy. Thus, schools are repeated as many times as there are courses associated with that school.
So, this is
<?php
while (have_posts()) :
the_post();
$school_items = get_field('shkola');
foreach ($school_items as $school_item) :
endforeach; ?>
<pre><?php print_r($school_item); ?></pre>
<?php endwhile; ?>
Gives me records containing duplicates
WP_Post Object ([ID] => 37)
WP_Post Object ([ID] => 37)
WP_Post Object ([ID] => 32)
I tried array_unique
, but I couldn't use it correctly, it still comes back with duplicates.
This is very similar to the situation here https://support.advancedcustomfields.com/forums/topic/strip-out-duplicate-content-from-an-array/, but the method described there also did not work for me.
I will be grateful for any help in this matter)
UPDATE
Output from print_r($school_items);
Array ([0] => WP_Post Object ( [ID] => 37 ) )
Array ([0] => WP_Post Object ( [ID] => 37 ) )
Array ([0] => WP_Post Object ( [ID] => 32 ) )
You could use a simple, have I seen this before test
<?php
$school_items = get_field('shkola');
if ($school_items) :
$seenIt = [];
foreach ($school_items as $school_item) :
if ( !in_array($school_item->ID, $seenIt) ) :
$title = get_the_title($school_item->ID);
?>
<div class="title">
<h2><?php echo esc_html($title); ?></h2>
</div>
<?php
$seenIt[] = $school_item->ID;
endif;
endforeach;
endif;
?>
Ok, so if you want to remove the duplicates from the original array as well this will also do that
$school_items = get_field('shkola');
if ($school_items) :
$seenIt = [];
foreach ($school_items as $key => $school_item) :
if ( in_array($school_item->ID, $seenIt) ) :
unset($school_items[$key]);
else:
$title = get_the_title($school_item->ID);
?>
<div class="title">
<h2><?php echo esc_html($title); ?></h2>
</div>
<?php
$seenIt[] = $school_item->ID;
endif;
endforeach;
endif;