Count within foreach loop

时间:2011-08-30 作者:Rob

如何在foreach循环中回显计数?我想更改下面div的类,使其成为menu-button-1、menu-button-2等:

    <?php 
$pages = get_children(array(\'orderby\' => \'menu_order\', \'order\' => \'asc\'));
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields();
?>

    <div class="menu-button-(insert counter here)">
        <a href="<?php echo get_page_link( $post->ID ); ?>"><?php echo $post->post_title; ?></a>
    </div>
<?php
}
wp_reset_query();
?>
所以我想让它输出这样的东西-<div class="menu-button-1"> 然后<div class="menu-button-2"> 等等,每次它通过循环。

1 个回复
最合适的回答,由SO网友:chrisguitarguy 整理而成

插入新的$counter 在foreach循环开始之前,以及在循环的最末端,调用$counter++ 以增加数字。在中间,只需回显$counter 变量

<?php 
$pages = get_children(array(\'orderby\' => \'menu_order\', \'order\' => \'asc\'));
// Add a counter before foreach starts
$counter = 1;
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields();
?>



<div class="menu-button-<?php echo $counter; /* echo out counter */ ?>">
        <a href="<?php echo get_page_link( $post->ID ); ?>"><?php echo $post->post_title; ?></a>
    </div>
<?php
$counter++; // increment before foreach ends
}
wp_reset_query();
?>

结束