如何从foreach循环中删除重复的结果

问题描述 投票:0回答:1

我正在尝试将一些侧边栏内容添加到我的WordPress搜索结果页面,在该页面上显示与当前搜索查询相关的顶部类别和标签。我已经能够生成内容,但是也显示了大量重复项。 Click for my example page

我已经尝试了两种方法,但都没有成功。两者都从以前的话题中被拉出,并带有类似的问题。如果可能,我宁愿避免使用第三方插件。任何想法,将不胜感激。谢谢

方法1:

function list_search_cats() {
  // Start the Loop
  $uniqueCats = array();
  while ( have_posts() ) : the_post();

    $cats = get_the_category();

    if (! in_array($cats, $uniqueCats)) :
      $uniqueCats[] = $cats;
      foreach($cats as $cat) :
        echo '<li><a class="tag" href="'.get_category_link($cat->cat_ID).'">' . $cat->cat_name . '</a></li>';
      endforeach;
    endif;

  endwhile;

}

方法2:

function list_search_cats() {
  // Start the Loop
  $uniqueCats = array();
  while ( have_posts() ) : the_post();

    $cats = get_the_category();
    $cats = array_unique($cats, SORT_REGULAR);

    foreach($cats as $cat) :
      echo '<li><a class="tag" href="'.get_category_link($cat->cat_ID).'">' . $cat->cat_name . '</a></li>';
    endforeach;

  endwhile;

}
wordpress loops foreach tags categories
1个回答
0
投票

在我看来,您只是缺少对每个类别的实际检查。您可能需要一个额外的foreach循环来检查重复项,然后在另一个foreach中使用该唯一数组来显示类别。试试这个:

function list_search_cats() {
  // Array to put unique cats in
  $uniqueCats = array();

  while ( have_posts() ) : the_post();

    $cats[] = get_the_category();


   // first foreach to check each cat and put in to new array 

    foreach($cats as $cat) {

      if(!in_array($cat, $uniqueCats)) {
         $uniqueCats[] = $cat;
      }

    }

   // second foreach to display the list

    foreach($uniqueCats as $cat_li) {

      echo '<li><a class="tag" href="'.get_category_link($cat_li->cat_ID).'">' . $cat_li->cat_name . '</a></li>';

    }

  endwhile;

}

© www.soinside.com 2019 - 2024. All rights reserved.