【问题标题】:How to handle variables in nested loops?如何处理嵌套循环中的变量?
【发布时间】:2013-03-15 15:19:52
【问题描述】:

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

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

但是,由于这是循环多个结果,我需要在每次迭代后将最终的 $i 数字存储在一个唯一变量中。

我应该如何处理?我可以在任何阶段使用我的$currentID 变量吗?

这是我的 PHP 的 sn-p 供参考:

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;

非常感谢您的任何指点 :-)

【问题讨论】:

  • 您的意思是在每次循环运行后存储一个包含 $i 值的数组吗?
  • 是的。因此,在每个循环结束时,我将在一个唯一的变量名内有一个 $i 总数。
  • 如果您发现自己在想“我想存储任意数量的命名变量”之类的想法,那么您实际上想要一个具有一组值的变量。阅读数组,你就会明白我的意思

标签: php arrays variables loops


【解决方案1】:

为什么不让一个数组通过$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 的值将存储在等于 $currentID 的键中。不要忘记在每次迭代后重置您的计数器!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2012-11-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多