在PHP中回显while循环之外的变量

时间:2015-01-08 12:34:20

标签: php wordpress while-loop advanced-custom-fields

我有一个PHP while循环,我试图在它之外回显$child_i的内容,我该怎么做?

<li>
    <div class="responsive-accordion-head"><span class="ico arrow-right"></span><?php the_sub_field('category_name'); ?> <span class="faq-counter">4 Questions</span></div>
        <?php if( have_rows('questions') ): $child_i = 0; ?>
            <!-- Trying to echo $child_i on the line below -->
            <div class="responsive-accordion-panel <?php echo($child_i); ?>">
                <?php while( have_rows('questions') ): the_row(); ?>
                    <div class="question">
                        <h6><?php the_sub_field('question'); ?></h6>    
                        <p><?php the_sub_field('answer'); ?></p>
                    </div>
                <?php $child_i++; endwhile; ?>
            </div>
        <?php endif; //if( get_sub_field('items') ): ?>
    </div>
</li>   

3 个答案:

答案 0 :(得分:0)

可以将结果放入您自己的数组中,然后通过数字

访问它
<li>
    <div class="responsive-accordion-head"><span class="ico arrow-right"></span><?php the_sub_field('category_name'); ?> <span class="faq-counter">4 Questions</span></div>
        <?php if( have_rows('questions') ): $child_i = 0; ?>
            <!-- Trying to echo $child_i on the line below -->
            <div class="responsive-accordion-panel <?php echo($child_i); ?>">
                <?php while( have_rows('questions') ): the_row(); ?>
                    <div class="question">
                        <h6><?php the_sub_field('question'); ?></h6>    
                        <p><?php the_sub_field('answer'); ?></p>
                    </div>
                <?php $results[] = $child_i; $child_i++; endwhile; ?>
            </div>
        <?php endif; 
print_r($results);
//OR foreach($results as $result){echo $result;} 
//OR echo $result[1].$result[1]; //etc
//if( get_sub_field('items') ): ?>
    </div>
</li>   

答案 1 :(得分:0)

最简单的方法是将您的班级移到while()循环中,然后使用计数器

实施例

<li>
    <div class="responsive-accordion-head"><span class="ico arrow-right"></span><?php the_sub_field('category_name'); ?> <span class="faq-counter">4 Questions</span></div>
        <?php if( have_rows('questions') ): $child_i = 0; ?>
            <!-- Trying to echo $child_i on the line below -->
                <?php while( have_rows('questions') ): the_row(); ?>

            <div class="responsive-accordion-panel <?php echo ($child_i); ?>">

                    <div class="question">
                        <h6><?php the_sub_field('question'); ?></h6>    
                        <p><?php the_sub_field('answer'); ?></p>
                    </div>

             </div>

                <?php $child_i++; endwhile; ?>
        <?php endif; //if( get_sub_field('items') ): ?>
    </div>
</li>   

答案 2 :(得分:-1)

尝试插入

echo '<xmp>'; var_dump($child_i); echo '</xmp>';

而不是

echo($child_i);

($ child_i可以包含空字符串)