Php 如何处理嵌套循环中的变量?
我的脚本在WordPress网站上的帖子中循环 我还计算了未发布帖子的数量,并将其存储在我的Php 如何处理嵌套循环中的变量?,php,arrays,variables,loops,Php,Arrays,Variables,Loops,我的脚本在WordPress网站上的帖子中循环 我还计算了未发布帖子的数量,并将其存储在我的$I变量中 但是,由于这是在多个结果之间循环,我需要在每次迭代后将最终的$I图形存储在一个唯一的变量中 我应该如何处理这个问题?我可以在任何阶段使用$currentID变量吗 以下是我的PHP代码片段供参考: while ( $query->have_posts() ) : $query->the_post(); $currentID = get_the_ID();
$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;
非常感谢所有的指针:-)为什么不让一个数组通过
$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
的键上。不要忘记在每次迭代后重置计数器 您的意思是在循环每次运行后总共存储一个$i值的数组吗?是的。因此,在每个循环结束时,我会在一个唯一的变量名中包含一个$I
总数。如果您发现自己想“我想存储任意数量的命名变量”,实际上您需要一个带有值数组的变量。读一下数组,你就会明白我的意思了