doucan2102 2010-11-09 01:31
浏览 218
已采纳

PHP foreach循环,比较两个值

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
---------------------------------------
  Nov 20   |    70 kg  |     -1 kg      << LAST LOGGED WEIGHT, FIRST IN ARRAY
.......................................
  Nov 15   |    71 kg  |      -
---------------------------------------
  • 写回答

2条回答 默认 最新

  • doutang6819 2010-11-09 01:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?