它在foreach循环中显示此结果,并且应删除所有重复项
spain
philippines
spain
我尝试使用array_unique(),但对我不起作用
这是我正在使用且可以正常工作的代码,只是它具有重复项
<?php
if (is_tax() || is_category() || is_tag() ){
$qobj = get_queried_object();
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $qobj->taxonomy,
'field' => 'slug',
'terms' => $qobj->slug
)
)
);
$random_query = new WP_Query( $args );
if ($random_query->have_posts()) {
while ($random_query->have_posts()) {
$random_query->the_post();
$term_list = wp_get_post_terms($post->ID, 'country', array("all"));
foreach($term_list as $term_single) {
echo '<a href="'.dirname(get_the_permalink()).'">';
echo $term_single->slug;
echo '</a><br>';
}
}
}
wp_reset_query();
}
?>
为调试添加了它-var_dump($ term_list);这就是结果
array (size=1)
0 =>
object(WP_Term)[1464]
public 'term_id' => int 2
public 'name' => string 'Spain' (length=5)
public 'slug' => string 'spain' (length=5)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 2
public 'taxonomy' => string 'country' (length=7)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 2
public 'filter' => string 'raw' (length=3)
array (size=1)
0 =>
object(WP_Term)[1473]
public 'term_id' => int 5
public 'name' => string 'Philippines' (length=11)
public 'slug' => string 'philippines' (length=11)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 5
public 'taxonomy' => string 'country' (length=7)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 2
public 'filter' => string 'raw' (length=3)
array (size=1)
0 =>
object(WP_Term)[1475]
public 'term_id' => int 2
public 'name' => string 'Spain' (length=5)
public 'slug' => string 'spain' (length=5)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 2
public 'taxonomy' => string 'country' (length=7)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 2
public 'filter' => string 'raw' (length=3)
我所需要的只是删除重复项,我已经准备好了,我对此不太熟悉,而且它非常复杂,自昨天以来,我正试图弄清楚这一点,请任何人帮助我使其正常运行或只是在正确的轨道,谢谢
答案 0 :(得分:1)
如果保留已显示列表的列表,则在显示新的列表之前,请检查该列表中是否包含该列表(使用in_array()
)。显示后,将其添加到已显示的列表中以使其不再显示...
$term_list = wp_get_post_terms($post->ID, 'country', array("all"));
foreach($term_list as $term_single) {
if ( !in_array( $term_single->slug, $alreadyDisplayed) ) {
echo '<a href="'.dirname(get_the_permalink()).'">';
echo $term_single->slug;
echo '</a><br>';
$alreadyDisplayed[] = $term_single->slug;
}
}
您将需要...
$alreadyDisplayed = [];
在行之前
while ($random_query->have_posts()) {