在foreach循环中回声计数

时间:2011-08-30 12:48:31

标签: php wordpress foreach

如何在foreach循环中回显计数?我想更改下面div的类,所以它的菜单按钮-1,菜单按钮-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 个答案:

答案 0 :(得分:4)

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

    <div class="menu-button-$i">
        <a href="<?php echo get_page_link( $post->ID ); ?>"><?php echo $post->post_title; ?></a>
    </div>
<?php
$i++;
}
wp_reset_query();
?>