开发者

PHP foreach loop where two values are compared

I'm building a simple weight log, where there'a table that display the user's progress. I'm using 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 ;?>

I'm trying to calculate the variation between the first row and the second row, so as to get the weight loss or gain between logs. I was wondering how to access the loop's previous record so as to substract it from the current record's weight.

---------------------------------------
  DATE     |   WEIGHT  |   VARIATION
--------------------开发者_如何学Go-------------------
  Nov 20   |    70 kg  |     -1 kg      << LAST LOGGED WEIGHT, FIRST IN ARRAY
.......................................
  Nov 15   |    71 kg  |      -
---------------------------------------


One simple way to do it:

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

Or, the reverse way:

<?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; ?>

If your array keys are guaranteed to be numeric (which they probably are), this can be simplified a lot. See @William's answer.


You could try using the key => value option for foreach (here). This would give you the current index in the log, so finding the previous index would be index = ($key == 0) ? $key : ($key - 1); $old_weight = $logs[$index]; (the syntax might be a bit off, but the idea is there).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜