while循环中值之间的差异

时间:2018-05-23 09:40:00

标签: php arrays while-loop

我试图在while循环中计算PHP中数组值之间的差异。 最初我使用(下一个)和(上一个)使用foreach循环,但它似乎不能很好地工作。

我现在尝试的实际上是可行的,但问题是计算的值应该实际出现在表的下一行。 这是表格和HTML:

        <table table id="meter_entries" class="table table-striped table-hover dt-responsive"><thead>
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Company Code</th>
                <th>Oil Height</th>
                <th>Water Height</th>
                <th>Total Volume</th>
                <th>Difference</th>
                <th>Actions</th>
            </tr>
            </thead>
            <?php 
            $s = $stock_automatic; $i=0; $count = count($s); 
            while($i < $count){ 
              ?>
              <tr>
                <td><?php echo $s[$i]['id']; ?></td>
                <td><?php echo $s[$i]['timess']; ?></td>
                <td><?php echo $s[$i]['company_code']; ?></td>
                <td><?php echo $s[$i]['oil_height']; ?></td>
                <td><?php echo $s[$i]['water_height']; ?></td>
                <td><?php echo $s[$i]['total_volume']; ?></td>
                <td><?php $oldvol = $s[$i-1]['total_volume']; $currvol = $s[$i]['total_volume'];  $diff =  $oldvol - $currvol; echo $diff; ?></td>
                <td>
                    <a href="<?php echo site_url('stock_automatic/edit/'.$s[$i]['id']); ?>" class="btn btn-info btn-xs"><span class="fa fa-pencil"></span> Edit</a> 
                    <a href="<?php echo site_url('stock_automatic/remove/'.$s[$i]['id']); ?>" class="btn btn-danger btn-xs"><span class="fa fa-trash"></span> Delete</a>
                </td>
              </tr>
              <?php 
               $i++; 
            } 
            ?>
        </table>

这是输出: Table

1 个答案:

答案 0 :(得分:1)

您的问题似乎是您正在使用数据表,而您的数组$s的实际排序方式与示例中显示的方式相反。

要获得正确的值,您应该将代码更改为以下

<?php if ($i==$count-1){
    echo '0';
}
else { 
    $oldvol = $s[$i+1]['total_volume']; $currvol = $s[$i]['total_volume'];  
    $diff =  $currvol - $oldvol; echo $diff;
} ?>