【问题标题】:Difference between values in while loopwhile循环中的值之间的差异
【发布时间】:2018-11-02 05:45:46
【问题描述】:

我正在尝试在 while 循环中计算 PHP 中数组值之间的差异。 最初我使用 (next) 和 (prev) 使用 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>

这是输出:

【问题讨论】:

  • 计算出来的值实际上应该出现在表格的下一行。你的意思是,对于 ID 39,你应该有那一行,然后在下一行你应该有 1 个只有区别的单元格?
  • 我实际上有一个 if 语句... if($i = 0){ echo $i;} else { THE CODE I HAVE ABOVE}。我把它拿出来用于stackoverflow,因为我还在研究它
  • 我可以从你的图片中看出你可能有数据表。我认为正在发生的是数据表强制执行的顺序实际上与$s 数组顺序相反。您可以停用数据表并再次回显该表以查看数据表排序之前的原始输出吗?
  • 我很想知道发生了什么,用一些虚拟数据复制您的示例非常有效。请注意,我已更改 $diff = $currvol - $oldvol 但这不是问题。 3v4l.org/GGYko
  • @Loek 似乎问题确实出在数据表上,因为它确实在没有数据表的情况下工作。嗯

标签: php arrays while-loop


【解决方案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;
} ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 2022-01-25
    • 2011-04-07
    • 2010-11-13
    • 2020-09-04
    • 2016-01-23
    相关资源
    最近更新 更多