代码之家  ›  专栏  ›  技术社区  ›  michaelmcgurk

如何处理嵌套循环中的变量?

  •  2
  • michaelmcgurk  · 技术社区  · 13 年前

    我的脚本循环浏览我的WordPress网站上的帖子。

    我也在计算未发布帖子的数量,并将其存储在我的 $i 变量

    然而,由于这是在多个结果中循环,我需要存储最终结果 $i美元 在每次迭代后以一个唯一的变量表示。

    我该如何处理? 我可以用我的吗 $currentID 在任何阶段都是可变的?

    以下是我的PHP代码片段供参考:

    while ( $query->have_posts() ) : $query->the_post();
    
        $currentID = get_the_ID();
    
            while ( $events_list->have_posts() ) :
    
                $events_list->the_post();
    
                $postdate = get_the_date('Y-m-d');
                $currentdate = date('Y-m-d');
    
                if ($postdate > $currentdate) {
                    $i++;
                }
    
            endwhile;
    
    // preferrably store the total of $i here in a unique variable then reset $i
    
        the_content();
    
    endwhile;
    

    非常感谢您的指点:-)

    1 回复  |  直到 13 年前
        1
  •  1
  •   Lix    13 年前

    为什么不让一个数组通过的键来保存所有值 $currentID ?

    $postCount = array();
    while(condition){
      $currentID = get_the_ID();
      $i = 0; // don't forget to reset your counter
      // processing goes here
      while(condition){
        // more processing goes here
        $i++;
      }
      $postCount[$currentID] = $i;
    }
    

    这将给您留下一个包含的值的数组 $i 对于外循环的每次迭代。的值 $i美元 将存储在等于 $当前ID 。不要忘记在每次迭代后重置计数器!

    推荐文章