首页 > 解决方案 > 在循环中多次使用 $I++

问题描述

我需要在许多地方使用 $i++ 的值,但如果我这样做,那么某些字段最终会跳过值,而不是 1、2、3 等。它们是 1、3、5,而另一个字段的值为 2 , 4, 6 等

<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
 <div>This number: <?php echo $i++; ?></div>
 <div>Should be the same as this one:  <?php echo $i++; ?></div>
<?php end while; ?>

如果我创建另一个变量,它会起作用,但这感觉就像一个黑客。

<?php $i = 1;
      $x = 1;
?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
 <div>This number: <?php echo $i++; ?></div>
 <div>Should be the same as this one:  <?php echo $x++; ?></div>
<?php end while; ?>

有没有更好的办法?

标签: php

解决方案


解决方案很简单——$i只增加一次

<?php $i = 1; ?>
<?php while (have_rows( 'something' ) ): the_row(); ?>
 <div>This number: <?php echo $i; ?></div>
 <div>Should be the same as this one:  <?php echo $i++; ?></div>
<?php end while; ?>

推荐阅读