为了账号安全,请及时绑定邮箱和手机立即绑定

显示两个价目表之间的差异

显示两个价目表之间的差异

PHP
青春有我 2023-06-24 15:55:59
我有产品价格的历史列表(按created_at排序),如下所示:Array(    [0] => stdClass Object        (            [id] => 1            [product_id] => 49            [price] => 14520000.0000            [created_at] => 1592501154        )    [1] => stdClass Object        (            [id] => 2            [product_id] => 49            [price] => 14000000.0000            [created_at] => 1592587554        )    [2] => stdClass Object        (            [id] => 4            [product_id] => 49            [price] => 14800000.0000            [created_at] => 1592673954        )    [3] => stdClass Object        (            [id] => 5            [product_id] => 49            [price] => 10000000.0000            [created_at] => 1592760354        )    [4] => stdClass Object        (            [id] => 6            [product_id] => 49            [price] => 14000000.0000            [created_at] => 1592846754        )    [5] => stdClass Object        (            [id] => 7            [product_id] => 49            [price] => 14000000.0000            [created_at] => 1592933154        )    [6] => stdClass Object        (            [id] => 8            [product_id] => 49            [price] => 14000000.0000            [created_at] => 1593019554        ))现在,为了在表中显示数据,我使用foreach如下方法列出了价格:   <?php foreach($product_prices_list as $product_price_list):?>     <tr>         <td><?= esc($product_price_list->created_at);?></td>         <td class="text-center"><?= esc(number_format($product_price_list->price));?></td>         <td class="text-center"></td> //show difference between of two price     </tr>   <?php endforeach;?>我可以在表中看到真实的输出,但我需要在第三列中显示两个价格之间的差异,如下图所示:我如何显示列表中两个价格之间的差异?!
查看完整描述

2 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

您只需将当前价格属性与数组中前一个对象的价格进行比较?


像这样的东西应该有效:


<?php foreach($product_prices_list as $key => $product_price_list):?>

    <tr>

        <td><?= esc($product_price_list->created_at);?></td>

        <td class="text-center"><?= esc(number_format($product_price_list->price));?></td>

        <td class="text-center"><?= (!empty($product_prices_list[$key - 1])) ? $product_prices_list[$key + 1]->price - $product_price_list->price: 0; ?></td> //show difference between of two price

    </tr>

<?php endforeach;?>


查看完整回答
反对 回复 2023-06-24
?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

如果您运行的是 MySQL 8.0,则可以使用窗口函数直接在数据库中计算此信息:


select

    t.*,

    price 

        - lag(price, 1, price) over(partition by product_id order by created_at) 

        as price_diff

from mytable t

这会向结果集中再添加一列,其中包含同一产品的当前价格与之前价格之间的差异。


查看完整回答
反对 回复 2023-06-24
  • 2 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信