PHP foreach循环,比较两个值

时间:2010-11-09 01:31:58

标签: php loops foreach

我正在构建一个简单的权重日志,其中有一个显示用户进度的表。我正在使用Codeigniter。

    <?php foreach($logs as $log) : ?>
        <tr>
        <td><?php echo $log->date ;?></td>
        <td><?php echo $log->weight ;?> kg.</td>
        <td><!-- variation between this record and previous record. weigth[a] - weight[b] --></td>
        <td></td>
        <td><?php echo anchor('logs/edit/'.$log->id, 'Editar'); ?> <?php echo anchor('logs/delete/'.$log->id, 'Delete'); ?></td>
        </tr>
    <?php endforeach ;?>

我正在尝试计算第一行和第二行之间的变化,以便获得日志之间的重量损失或增益。我想知道如何访问循环的先前记录,以便从当前记录的权重中减去它。

---------------------------------------
  DATE     |   WEIGHT  |   VARIATION
---------------------------------------
  Nov 20   |    70 kg  |     -1 kg      << LAST LOGGED WEIGHT, FIRST IN ARRAY
.......................................
  Nov 15   |    71 kg  |      -
---------------------------------------

2 个答案:

答案 0 :(得分:5)

一种简单的方法:

<?php $previousWeight = null; ?>
<?php foreach($logs as $log) : ?>
    <tr>
    <td>
        <?php
            if ($previousWeight) {
                echo $previousWeight - $log->weight;
            }
            $previousWeight = $log->weight;
        ?>
    </td>
    </tr>
<?php endforeach; ?>

或者,相反的方式:

<?php
    $current = current($logs);
    $next = next($logs);
?>
<?php while ($current) : ?>
    <tr>
        <td><?php echo $current->date; ?></td>
        ...
        <td>
            <?php
                if ($next) {
                    echo $current->weight - $next->weight;
                }
            ?>
        </td>
    </tr>
    <?php
        $current = $next;
        $next = next($logs);
    ?>
<?php endwhile; ?>

如果您的数组键保证是数字(可能是它们),这可以简化很多。请参阅@William's answer

答案 1 :(得分:1)

您可以尝试使用key => valuehere)的foreach选项。这将为您提供日志中的当前索引,因此查找上一个索引将为index = ($key == 0) ? $key : ($key - 1); $old_weight = $logs[$index];(语法可能有点偏离,但想法就在那里)。