【问题标题】:Foreach in a foreach and filtering through both of them在 foreach 中进行 foreach 并通过它们进行过滤
【发布时间】:2013-01-16 13:49:42
【问题描述】:

我正在尝试通过通过 wordpress 中的类别链接的帖子显示相关帖子,但我无法过滤结果。

这是我目前的代码:

     $current_post = $post->ID;
         $i = 0;
         $categories = get_the_category();
         foreach ($categories as $category) {            
            $posts = get_posts('numberposts=4&category='. $category->term_id . '&exclude=' . $post->ID);
                foreach($posts as $post) { 
                                     // DO BASIC ECHO POST CONTENT STUFF

                     $i++;
                     if ($i == 3) break;
                         }
           } 


wp_reset_query();

我的代码的问题是,当一个帖子属于 3 个类别时(即使这不是好的网络实践),这个循环会回显 12 个帖子(每个类别 4 个帖子)并且如果不同的文章属于相同的 3 个类别,显示 3 次(重复)。我想显示 MAX 4 个帖子,并且没有重复。

我认为 $i == 3 break;将使其在第一个“全局”4 个结果之后停止。但它没有?以及如何才能使结果中没有重复的结果?

【问题讨论】:

  • 函数get_posts()不能在sql端使用GROUP BY做任何过滤吗?
  • 你打破只会停止帖子循环。如果要停止两次循环,请尝试使用if ($i == 3) break 2;
  • 您需要更清楚地解释您想要输出的内容。或许你可以举个例子。
  • foreach($posts as $post) {} 循环之外增加$i
  • 谢谢大家,但这次 spin0us 成功了!我也需要打破 foreach 类别,但我没有意识到这一点!谢谢 :) 如何将其标记为已解决并得到正确答案?

标签: php wordpress foreach


【解决方案1】:

您可以创建显示帖子的数组,然后检查该数组中的帖子是否显示它。

$show_array = array();

// ...

foreach($posts as $post) { 
   if (!in_array($post['id'], $show_array)) {
       // show post
       $show_array[] = $post['id'];
   }
}

【讨论】:

    【解决方案2】:
    $current_post = $post->ID;
             $i = 0;
             $categories = get_the_category();
             foreach ($categories as $category) {            
                $posts = get_posts('numberposts=4&category='. $category->term_id . '&exclude=' . $post->ID);
                    foreach($posts as $post) { 
                                         // DO BASIC ECHO POST CONTENT STUFF
    
                         $i++;
                         if ($i == 3) break 2;
                             }
               } 
    

    wp_reset_query();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2010-12-24
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      相关资源
      最近更新 更多