简体   繁体   中英

PHP While Loop setting count ID

I'm a little stuck with a piece of PHP I am working on, I need to set the href of a link to the same ID for the DIV below it, but its not setting them the same.

$x=1; 
     while ( $loop->have_posts() ) : $loop->the_post(); 
     if($color!='')
        {
            $out.='<'.$heading.' class="heading_accordion newHeadingColor">'.get_the_title().'</'.$heading.'>';
        }
     else
     {
                $out.='<dd class="accordion-navigation"><a href="#panel'.$x++.'">'.get_the_title().'</a>';
     }
                $out.= '<div id="panel'.$x++.'" class="content">'.get_the_content().'</div></dd>';

                endwhile; // end of the loop.

its doing

<a href="#panel1">link</a>
<div id="panel2">content</div>
<a href="#panel3">link</a>
<div id="panel4">content</div>
<a href="#panel5">link</a>
<div id="panel6">content</div>

and need something like

<a href="#panel1">link</a>
<div id="panel1">content</div>
<a href="#panel2">link</a>
<div id="panel2">content</div>
<a href="#panel3">link</a>
<div id="panel3">content</div>

It's because you are incrementing $x twice : Once when you output the href, once when you output the id.

You could just remove the incrementation on the first output :

$out.='<dd class="accordion-navigation"><a href="#panel'.$x.'">'.get_the_title().'</a>';

And keep it in the second one :

$out.= '<div id="panel'.$x++.'" class="content">'.get_the_content().'</div></dd>';

try this

while ( $loop->have_posts() ) : $loop->the_post(); 
$x++;
     if($color!='')
        {
            $out.='<'.$heading.' class="heading_accordion newHeadingColor">'.get_the_title().'</'.$heading.'>';
        }
     else
     {
                $out.='<dd class="accordion-navigation"><a href="#panel'.$x.'">'.get_the_title().'</a>';
     }
                $out.= '<div id="panel'.$x.'" class="content">'.get_the_content().'</div></dd>';

            endwhile; // end of the loop.

$x++

is equal to

$x = $x + 1

so you increment this 2 times in 1 iteration. Try to remove increment from one of this two segments.

<?php
$x=1; 
while ( $loop->have_posts() ) : $loop->the_post();

if($color!='') {
    $out.='<'.$heading.' class="heading_accordion newHeadingColor">'.get_the_title().'</'.$heading.'>';
} else {
    $out.='<dd class="accordion-navigation"><a href="#panel'.$x.'">'.get_the_title().'</a>';
}
$out.= '<div id="panel'.$x.'" class="content">'.get_the_content().'</div></dd>';

$x++;
endwhile; // end of the loop.
?>

You are doing the $x++ to early.

Just use $x to output the id and do $x++ after the if-else statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM