michaelmcgurk
michaelmcgurk

Reputation: 6509

How to handle variables in nested loops?

My script loops through posts on my WordPress site.

I'm also counting the number of unpublished posts and storing it in my $i variable.

However, as this is looping through multiple results, I need to store the final $i figure in a unique variable after each iteration.

How should I handle this? Could I use my $currentID variable at any stage?

Here is a snippet of my PHP for reference:

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;

Many thanks for any pointers :-)

Upvotes: 2

Views: 269

Answers (1)

Lix
Lix

Reputation: 47966

Why not have an array holding all of the values by a key of $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;
}

That will leave you with an array containing the value of $i for each iteration of the outer loop. The values of $i will be stored at a key equal to $currentID. Don't forget to reset your counter after each iteration!

Upvotes: 1

Related Questions