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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧