2013-03-25 60 views
2

我的腳本通過我的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

你的意思是在每次運行循環後存儲$ i的值的數組? – Patashu 2013-03-25 23:32:06

+0

是的。所以在每個循環結束時,我會在一個唯一的變量名稱中有一個「$ i」總數。 – michaelmcgurk 2013-03-25 23:35:35

+1

如果你發現自己在想像'我想存儲任意數量的命名變量',你實際上需要一個具有數值數組的變量。閱讀關於陣列,你會看到我的意思 – Patashu 2013-03-25 23:36:33

回答

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的密鑰中。不要忘記在每次迭代後重置計數器!

+0

酷 - 讓我試試這個,我會馬上回來:) – michaelmcgurk 2013-03-25 23:36:52

+0

這工作完美!非常感謝 !! :) – michaelmcgurk 2013-03-25 23:39:57

+1

@mic - 高興地幫忙! :) – Lix 2013-03-25 23:42:29