通过 foreach 函数进行筛选


Filtering through a foreach function

我在这里拔头发,我根本无法让它工作。

我需要

做一个foreach循环来获取网站中的所有作者,然后我需要过滤掉那些发表文章为0的作者,然后将带有文章的作者回显到UL LI中,并为数组中的最后一个作者提供特殊

  • 标签:

    我现在的代码有两个函数,一个用于预过滤至少拥有一篇文章的所有作者,然后在第二个函数中计算过滤数组中剩余的作者数量,然后给数组中的最后一个条目一个特殊的 li 标签。到目前为止的代码:

    /*********************
        Echo Filtered List
        *********************/
        function filtered_list() {
            $authors = get_users('orderby=nicename');
            $all_authors = array();
             if ( count_user_posts( $author->id ) >= 1 ) {
                 return true;
            }
        }
    
        function contributors() {
        $i = 0;
        filtered_list();
        $len = count($all_authors);
        foreach ($all_authors as $author ) {
              if ( count_user_posts( $author->id ) >= 1 ) {
                    if ($i == $len - 1) {
                        echo "<li class='author-last clearfix'>";}
                    else {
                        echo "<li class='author clearfix'>";}
                    $i++;
    
  • 如果你通读你的代码,你可能会明白为什么它不起作用。

    第一:作用域

    阅读 PHP 手册中的变量作用域。基本上,在函数内声明的变量仅在该函数中可用,因此$all_authors 在 contributors() 中为 null,因为它从未被初始化过。

    filtered_list 函数应返回经过筛选的作者列表,因此您应该循环(尽管$authors并将作者添加到 $all_authors if 且仅当她有 1 个或多个帖子时。循环后,返回数组。

    现在,您可以通过将 fist 函数的返回值设置为 contributors 中的 $all_authors 来获取过滤列表(或者更好的是,只需将它们称为 $authors )。

    现在,您已准备好遍历作者列表并找到他们的帖子。为此,您需要两个循环。一个用于作者,一个用于帖子。

    foreach author in authors
        foreach post in author->posts
            if post is last post
                print special stuff
            else
                print normal stuff
            endif
        endforeach
    endforeach
    

    希望这有所帮助,并且您会从中学到一些东西。要点是:逐行阅读您的代码,并向自己解释它的作用。